| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 390 人关注过本帖
标题:文件创建写入和读取问题
只看楼主 加入收藏
tottibuffon
Rank: 2
等 级:论坛游民
帖 子:105
专家分:20
注 册:2009-6-5
结帖率:83.87%
收藏
已结贴  问题点数:10 回复次数:1 
文件创建写入和读取问题
import *;

public class File1Writer {

    public static void main(String[] args) {
    try {
        long dataPosition = 000; //to be determined later
        int data = 100;
            RandomAccessFile raf = new RandomAccessFile("file1", "rw");

        //Write the file.
        raf.writeLong(0); //placeholder
        raf.writeChars("I won't forget the way you kiss me\n");/** writeChars(String) 则是将字符串的每个字符的
                                                                   高8位和低8位分别转成字节
                                                                   就是说一个字符变成两个自己的方式 **/

        dataPosition = raf.getFilePointer();
        raf.writeInt(data);
        raf.writeUTF("that's why you go that I know");//writeUTF 是将字符串以UTF8编码方式输出 数据可以通过readUTF读回来


        //Rewrite the first byte to reflect updated data position.
        raf.seek(0);
        raf.writeLong(dataPosition);
        raf.close();

    } catch (FileNotFoundException e) {
        System.err.println("This shouldn't happen: " + e);
    } catch (IOException e) {
        System.err.println("Writing error: " + e);
    }
    }
}



import *;

public class File1Reader {

    public static void main(String[] args) {
    try {
        long dataPosition = 0;
        int data = 0;
        String s1;
            RandomAccessFile raf = new RandomAccessFile("file1", "r");

        //Get the position of the data to read.
        dataPosition = raf.readLong();

        //Go to that position.
        raf.seek(dataPosition);

        //Read the data.
        data = raf.readInt();
        dataPosition=raf.readLong();
        raf.close();

        //Tell the world.
        System.out.println("The data is: " + data+"\nThe datePosition is: "+dataPosition);

    } catch (FileNotFoundException e) {
        System.err.println("This shouldn't happen: " + e);
    } catch (IOException e) {
        System.err.println("Writing error: " + e);
    }
    }
}

问题:应该通过什么方法把字符串给读出来?  试过raf.readChar()可是编译出错。还有这些read和write的方法在import 中哪个类里面可以查?
搜索更多相关主题的帖子: 文件 
2009-10-20 16:53
gameohyes
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:湖南
等 级:版主
威 望:53
帖 子:1275
专家分:3629
注 册:2009-3-5
收藏
得分:7 
read和write的方法在import 中哪个类里面可以查?
你有API的话。目录旁边有个索引输入你想查的方法
下面那个题
后面加个throws Exception试下
如:public static void main(String[] args) throws Exception

C#超级群 74862681,欢迎大家的到来!
2009-10-20 20:13
快速回复:文件创建写入和读取问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014483 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved