输入输出流最容易忽略的细节就是使用完要记得用close()方法关闭!!!
InputStream 字节输入流
inputStream核心方法read(),通过while循环读取文件到创建好的buf数组里面。当读到文件末尾的时候最后一个数值会是-1,因此这就是终止条件。而直接输入的字节可能会中文乱码,所以需要手动转GBK或者UTF-8。available() 方法可以返回文件长度。
//FileInputStream里面输入要读取的文件路径
FileInputStream in = new FileInputStream("D:\\test.txt");
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {String s = new String(buf, 0,len,"UTF-8");System.out.println(s);
}
in.close();
OutputStream字节输出流的使用
核心方法write(),作用是将数据流写出到文件里。首先要将数据流读取到一个数组里然后再写出到另一个文件。
FileInputStream in = new FileInputStream("D:\\test.txt");
FileOutputStream out = new FileOutputStream("D:\\test1.txt");
byte[] buf = new byte[1024];
int len;
//循环写入buf中
while ((len = in.read(buf)) != -1) {out.write(buf,0,len);
}
in.close();
out.close();
Reader字符输入流的使用
提供了自动转码的功能解决中文字符乱码,但本质用的还是inputStream
FileReader fileReader = new FileReader("D:\\test.txt");
int len;
char[] buf = new char[1024];
while ((len = fileReader.read(buf)) != -1) {String s = new String(buf, 0,len);System.out.println(s);
}
fileReader.close();
Writer字符输出流的使用
结束的时候需要调用flush()方法,当然close()也包含了
FileReader fileReader = new FileReader("D:\\test.txt");
FileWriter out = new FileWriter("D:\\test1.txt");
int len;
char[] buf = new char[1024];
while ((len = fileReader.read(buf)) != -1) {out.write(buf,0,len);
}
//close 包含了out.flush()
out.close();
fileReader.close();
BufferedReader和BufferedWriter的使用
之前都需要手动去创建一个buf数组作为暂存缓存然后再进行输出而BufferedReader和BufferedWriter就解决了这个临时数据存储的问题,同时提供了readLien()方法一行一行去读取数据。而创建好的BufferedReader或者BufferedWriter里面都需要先实现先在方法里创建一个Reader或者Writer
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\test.txt"));
String str = null;
while ((str = bufferedReader.readLine()) != null){System.out.println(str);
}BufferedReader bufferedReader = new BufferedReader(new FileReader("D:\\test.txt"));
Stream<String> lines = bufferedReader.lines();
lines.forEach(System.out::println);
BufferedReader in = new BufferedReader(new FileReader("D:\\test.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("D:\\test.txt"));
int len ;
char [] buf = new char[1024];
while ((len = in.read(buf)) != -1){out.write(buf,0,len);
}
in.close();
out.close();