RandomAccessFile
随机存取的二进制文件
//构造的第二参数表示操作的模式,r表示读 w表示写
RandomAccessFile ra = new RandomAccessFile(new File("E:\\abc\\ra.txt"),"rw");
//设置大小为2k
ra.setLength(2048);
ra.writeInt(500);
ra.writeUTF("你好");
//从1k的位置开始写
ra.seek(1024);
ra.writeUTF("abc");
Properties
键值对存取文件(一般可以用作一些配置文件)
读:
FileInputStream in = new FileInputStream("E:\\abc\\config.ini");
//创建Properties
Properties p = new Properties();
//加载文件
p.load(in);
//按键取值
String color = p.getProperty("color");
//带默认值的读取
String abc = p.getProperty("abc", "默认值");
String fontSizeStr = p.getProperty("fontSize");
//关闭流
in.close();
写:
//输出流关联要写到的文件
FileOutputStream out = new FileOutputStream("E:\\abc\\config.ini");
Properties p = new Properties();
//设置要保存的属性(键值对)
p.setProperty("fontSize", "2000");
p.setProperty("color", "blue");
p.setProperty("mode", "night");
p.setProperty("menuType", "right");
//保存
p.store(out, "122222");
//关闭流
out.flush();
out.close();
注意:修改内容不覆盖原来的内容一定要先用输入流加载文件到Properties中,关闭输入流之后修改再保存,如:
FileInputStream in = new FileInputStream("E:\\abc\\config.ini");
//创建Properties
Properties p = new Properties();
//加载文件
p.load(in);
in.close(); //修改之前关闭
//设置要保存的属性(键值对)
p.setProperty("fontSize", "20");
p.setProperty("color", "red");
FileOutputStream out = new FileOutputStream("E:\\abc\\config.ini");
//保存
p.store(out, "aaaaaa");
out.flush();
out.close();
PrintWriter
//创建打印机对象,第二个参数autoFlush可以省略,加上为true的意思是自动刷新缓冲区
PrintWriter pw = new PrintWriter(new FileOutputStream(
"E:\\abc\\print.txt"),true);
//输出内容(不换行)
pw.print("Hello123");
//换行输出
pw.println("你好abc");
//关闭
pw.close();