学习了java 的io 自己总结下,总共可以用到的有两类,字节流和字符流。
字节流主要有 以Stream结尾的流,包括,InputStream、OutputStream、BufferedInputStream、BufferedOutputStream
FileInputStream、 FileOutputStream
字符流主要以 Reader结尾的流 包括 FileOutputReader、 FileInputReader BufferedReader、BufferedWriter
以及包括字节流到字符流的转换,进行解码编码 InputStreamReader OutputStreamWriter
package com.ssm.test;
import org.junit.Test;
import java.io.*;
/**
* @Author: zhouheng
* @Created: with IntelliJ IDEA.
* @Description:
* @Date: 2018-03-21
* @Time: 23:11
*/
public class TestOther {
@Test
public void test() {
BufferedWriter bw = null;
BufferedReader br = null;
try {
File file = new File("e:/logs/log.log");
File file2 = new File("e:/logs/log3.log");
// 读取字符流
FileInputStream fis = new FileInputStream(file);
// 转换字节流
InputStreamReader isr = new InputStreamReader(fis, "GBK");
// 设置缓冲流
br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(file2);
OutputStreamWriter osr = new OutputStreamWriter(fos, "GBK");
bw = new BufferedWriter(osr);
String str;
int len;
while ((str = br.readLine()) != null) {
System.out.println(str);
bw.write(str + "\n");
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这个程序主要是以字符流的形式读入文件,然后转换为字节流,然后再进行缓存流的读取,速度较快。
字节流可以读取任意的文件,声音视频,而字符流只可以读取文本文件。