现在我要对文件进行,读写修改操作,可能文件会比较大,到2M左右
1。 如何对文件进行缓冲,
2。修改文件是不是只有全部读出后找到修改点,然后重新存储
3。是不是用FileWriter等读取文件是不是会导致文件清空
这三个问题都和RandomAccessFile类有关系
这个类自动缓冲文件,并且可以对文件随机访问,可以指定文件指针跳到文件的某个位置
再进行操作,使用这个类来追加数据的时候,只需要把文件指针跳到最后,直接写数据就完了,
不会造成文件清空,比如:
File f=new File("1.txt");
RandomAccessFile raf=new RandomAccessFile(f,"rw");
raf.skipBytes((int)raf.length()); //文件指针跳到文件尾
raf.writeBytes("hello");
tring line = null;
int val = 0;
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(System.in));
line = is.readLine();
val = Integer.parseInt(line);
} catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
System.out.println("I read this number: " + val);