文件创建写入和读取问题
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 中哪个类里面可以查?