流可以被看作一组有序的字节集合,即数据在俩设备之间的传输。
流的本质是数据传输。根据处理数据类型的不同,流可以分为两大类:字节流和字符流。字节流以字节(8bit)为单位,包含两个抽象类:InputStream和OutputStream。字符流以字符(16bit)为单位,一次可以读取多个字节,它包含两个抽象类:Reader和Writer。字节流与字符流最主要的区别是:字节流在处理输入输出时不会用到缓存,而字符流用到了缓存。两者读取的都是文件中的二进制数据,字符流会把数据转换成我们能识别的字符,而字节流不会作任何处理。
1.FileInputStream读取文件
File file = new File("C:\\a.txt");
FileInputStream fis = new FileInputStream(file);
byte buf[] = new byte[1024];
int length = 0;
while (-1 != (length = fis.read(buf))) {
System.out.print(new String(buf, 0, length));
}
fis.close();
2.FileOutputStream写入文件
File file = new File("C:\\a.txt");
FileOutputStream fos = new FileOutputStream(file);// 若目标文件不存在,会自动创建;否则会覆盖原来的文件再写入数据。若要在文件末尾追加则使用构造方法FileOutputStream(file,true)
String data = "写入的数据";
fos.write(data.getBytes("UTF-8"));// 防止中文乱码
fos.flush();// 清空缓冲区
fos.close();
3.缓冲输入字符流(BufferedReader)读取文件
File file = new File("C:\\a.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();