代码如下:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test1 {
public static void main(String[] args) throws IOException {
/**
* 写一个字符串到文件里面去
*/
RandomAccessFile raf = new RandomAccessFile("demo.txt","rw");
String input = "helloWorld! 张三";
byte[] arr = input.getBytes();
raf.write(arr);//写入文件
raf.close();
/**
* 取出demo.txt中的内容
*/
RandomAccessFile raf2 = new RandomAccessFile("demo.txt","r");
byte[] bu = new byte[(int) raf2.length()];
raf2.read(bu);
System.out.println(new String(bu).trim());
raf2.close();
}
}
测试结果如下:
helloWorld! 张三