2022-03-07 12:00:53 晓掌柜 版权声明:本文为站长原创文章,转载请写明出处
按照流的流向分,可以分为输入流和输出流;
按照操作单元划分,可以划分为字节流和字符流;
按照流的角色划分为节点流和处理流。
Java Io 流共涉及 40 多个类,这些类看上去很杂乱,但实际上很有规则,而且彼此之间存在非常紧密的联系, Java I0 流的 40 多个类都是从如下 4 个抽象类基类中派生出来的。
InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。
OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。
①字节流读取文件内容 (输出文件内容 : this is a test data. 你好)
private static void inputStreamRead() throws IOException{
FileInputStream fis = new FileInputStream("D:\xa.txt");
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bt = new byte[1024];
int len;
while ((len = bis.read(bt))!= -1) {
System.out.println(new String(bt,0,len));
}
bis.close();
fis.close();
}
②字节流写入文件内容(hello world .你好)
private static void outputStreamWrite() throws IOException{
FileOutputStream fos = new FileOutputStream("D:\x.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write("hello world.你好".getBytes());
bos.close();
fos.close();
}
③字符流读取文本(输出同①)
private static void fileReadRead() throws IOException{
FileReader fir = new FileReader("D:\xa.txt");
BufferedReader bfr = new BufferedReader(fir);
String line;
while ((line = bfr.readLine()) != null) {
System.out.println(line);
}
bfr.close();
fir.close();
}
④字符流写入文件
private static void fileWriteWrite() throws Exception{
FileWriter fiw = new FileWriter("D:\x.txt");
BufferedWriter bfw = new BufferedWriter(fiw);
bfw.write("this is a test data. 你好啊");
bfw.close();
fiw.close();
}