缓存流
可以使用flush将缓存中的数据立即写入硬盘(不使用flush则会等缓存满了后再读取)
并且可以使用.mkdirs(),创建父类文件夹。
package file;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class TestStreamFlush {
public static void main(String[] args) {
//该文件父目录不存在,所以会报错,不会自动创建
File f = new File("d:/LOL/LOL2.txt");
File dir = f.getParentFile();
if(!dir.exists()){
dir.mkdirs();//使用mkdir,如果父类的父类不存在会报错
}
//缓存流必须建立在一个存在的流之上
try(FileWriter fr = new FileWriter(f);
PrintWriter pw = new PrintWriter(fr)){
pw.println("first line!");
//将缓存中的数据强制写入硬盘
pw.flush();
pw.println("second line!");
pw.flush();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
向文件中写入两个数字,再分别读取出来。(如输入777@4396),此处的重点在Input和Output,指的是从缓存中写出至硬盘,和重硬盘中写入缓存。in和out相对的是缓存。
方法一:使用缓存流
使用缓存流把两个数字以字符串的形式写到文件里,再用缓存流以字符串的形式读取出来,然后转换为两个数字。
private static void method1() {
File f = new File("D:/LOL.txt");
try(FileWriter fWriter = new FileWriter(f);
PrintWriter pWriter = new PrintWriter(fWriter);
) {
pWriter.println("777 4396");
pWriter.flush();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try(FileReader fReader = new FileReader(f);
BufferedReader bReader = new BufferedReader(fReader)) {
while(true){
String line = bReader.readLine();
if(null == line)
break;
String[] ss = line.split(" ");
int a = Integer.parseInt(ss[0]);
int b = Integer.parseInt(ss[1]);
System.out.printf("使用缓存流读取的数为%d和%d\n", a,b);
}
System.out.println("提取结束");
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
方法二:使用DataOutputStream,就可以直接写入和读取数,不用分隔符。
private static void method2(){
File f = new File("D:/LOL2.txt");
try (FileOutputStream fOutputStream = new FileOutputStream(f);
DataOutputStream dataOutputStream = new DataOutputStream(fOutputStream)){
dataOutputStream.writeInt(777);
dataOutputStream.writeInt(4396);
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try (FileInputStream fileInputStream = new FileInputStream(f);
DataInputStream dataInputStream = new DataInputStream(fileInputStream)){
int c = dataInputStream.readInt();
int d = dataInputStream.readInt();
System.out.printf("用数据流读取的数为%d和%d", c,d);
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
运行后结果为:
使用缓存流读取的数为777和4396
提取结束
用数据流读取的数为777和4396