1. IO流体系
2. 文件读写示例
public class FileIOTest {
/**
* 二进制文件读写——文件复制
*/
@Test
public void test1() {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File srcFile = new File("1.jpg");
File destFile = new File("2.jpg");
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
// 复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
// 刷新缓冲区
// bos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 资源关闭
// 要求:先关闭外层的流,再关闭内层的流
// 说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
if (bos != null) {
try {
bos.close(); // 关闭流会自动调一次flush()方法
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// fos.close();
// fis.close();
}
}
/**
* 文本文件的读写——复制文件
*/
@Test
public void test2() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
// 创建文件和相应的流
br = new BufferedReader(new FileReader(new File("hello.txt")));
bw = new BufferedWriter(new FileWriter(new File("hello1.txt")));
// 读写操作
// 方式一:使用char[]数组
/*char[] cbuf = new char[1024];
int len;
while ((len = br.read(cbuf)) != -1) {
bw.write(cbuf, 0, len);
// bw.flush();
}*/
// 方式二:使用String
String data;
while ((data = br.readLine()) != null) {
// 方法一:
// bw.write(data + "\n");//data中不包含换行符
// 方法二:
bw.write(data);// data中不包含换行符
bw.newLine();// 提供换行的操作,这个操作会根据操作系统的不同,使用对应操作系统的换行符
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 转换流——处理文件乱码问题
* 1.转换流:属于字符流
* InputStreamReader:将一个字节的输入流转换为字符的输入流
* OutputStreamWriter:将一个字符的输出流转换为字节的输出流
*
* 2.作用:提供字节流与字符流之间的转换
*
* 3. 解码:字节、字节数组 --->字符数组、字符串
* 编码:字符数组、字符串 ---> 字节、字节数组
*
*
* 4.字符集
* ASCII:美国标准信息交换码。
* 用一个字节的7位可以表示。
* ISO8859-1:拉丁码表。欧洲码表
* 用一个字节的8位表示。
* GB2312:中国的中文编码表。最多两个字节编码所有字符
* GBK:中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
* Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
* UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
*/
@Test
public void test3() {
File file1 = new File("hello.txt");
File file2 = new File("hello-gbk.txt");
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file1), StandardCharsets.UTF_8));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2), "gbk"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}