RandomAccessFile是读写都可以操作的io类,并且可以浮标标记所要开始读写的位置
以下为简单的实例
package com.test.first;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
public class RandomFile {
public static void main2(String[] args)
{
try
{
File f = new File("D:/project/EclipseWorkSpace/jsfdemo/src/testIo");
RandomAccessFile s = new RandomAccessFile(f,"rw");
byte[] b = new byte[(int) f.length()];
System.out.println(f.length());
System.out.println(s.length());
s.readFully(b);
System.out.println(new String(b));
System.out.println(s.getFilePointer());
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
try {
RandomAccessFile f = new RandomAccessFile("D:/project/EclipseWorkSpace/jsfdemo/src/testIo", "rw");
System.out.println("File.lelngth:"+(f.length( ))+"B");
//f.writeUTF("hellofewfewendendend");
f.writeBoolean(true);
f.writeBoolean(false);
f.writeChar('r');
f.writeChars("hello!!!");
System.out.println("File.lelngth:"+(f.length( ))+"B");
f.seek(0);
System.out.println(f.readBoolean());
System.out.println(f.readBoolean());
System.out.println(f.readLine());
f.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文通过两个示例展示了如何使用Java的RandomAccessFile类进行文件的读写操作。包括如何打开文件、读取文件内容并打印,以及如何写入布尔值、字符等数据类型到文件中。
1041

被折叠的 条评论
为什么被折叠?



