流的分类:
按流向区分:输出流:OutpuSteam和Write作为基类
输入流 :InpStream和Reader作为基类
按照处理数据单元划分:字节流:字节输入流InputStream基类
字节输出流OutStream基类
字符流: 字符输出流Reader基类
字符输入流Writer基类
字节流:程序→字节流→文件
字符流:程序→字符流→缓冲区→文件
举例:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.stream.Stream;
import java.io.FileOutputStream;
public class StreamTest {
public static void ByteWrite() {
File file = new File(“D:\test\test.txt”);
try {
OutputStream outputStream = new FileOutputStream(file);
String textString = “Hello World!!!”;
byte[] data = textString.getBytes();
outputStream.write(data);
}catch(IOException e) {
System.out.println("字节流写入文件出错。");
e.printStackTrace();
}
}
public static void main(String[] args) {
StreamTest.ByteWrite();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Test4 {/**
* 文件读取
*/
public static void readFile(){
File file=new File(“D:/test/test.txt”);
try {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), “utf8”);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
//循环输出每一行内容
while ((lineTxt = bufferedReader.readLine()) != null) {
System.out.println(lineTxt);
}
read.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Test4.readFile();
}
}