使用FileOutputStream的writer方法进行复制的时候出现一些细节问题,
发现理解的还是不够清楚,写个测试加深一下理解
测试中主要使用:
FileInputStream的 read() 和 read(byte[] b) 方法
FileOutputStream的 write(byte[] b)、write(int b) 和 write(byte[] b, int off, int len) 方法
根据api可知:
FileInputStream: 是从文件系统中的某个文件中获得输入字节,用于读取诸如图像数据之类的原始字节流
FileOutputStream: 是用于将数据写入 File 或 FileDescriptor 的输出流,用于写入诸如图像数据之类的原始字节的流
read(): 从此输入流中读取一个数据字节
read(byte[] b): 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
write(int b): 将指定字节写入此文件输出流
write(byte[] b): 将 b.length 个字节从指定 byte 数组写入此文件输出流中
write(byte[] b, int off, int len): 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流
按照读取一个数据字节写一个数组字节的方式,文本复制成功
/*
* 使用 read() write(int b)方法
*/
public static void fileCopy() throws Exception {
FileInputStream in = new FileInputStream("D:/a.txt");
FileOutputStream out = new FileOutputStream("D:/b.txt");
int length = 0;
while ((length = in.read()) != -1) {
System.out.println("读取:" + length);
out.write(length);
}
System.out.println("copy完成");
in.close();
out.close();
}
按照字节数组复制,写入方法使用write(byte[] b),文本末出现乱码
/*
* 使用 read(byte[] b) write(byte[] b)方法
* 文字大致相同,末尾部分出现部分乱码
*/
public static void fileCopy2() throws Exception {
FileInputStream in = new FileInputStream("D:/a.txt");
FileOutputStream out = new FileOutputStream("D:/b.txt");
byte[] buffer = new byte[1024];
while ((in.read(buffer)) != -1) {
out.write(buffer);
}
System.out.println("copy完成");
in.close();
out.close();
}
按照字节数组复制,写入方法使用write(byte[] b, int off, int len),文本一致
/*
* 使用 read(byte[] b) write(byte[] b, int off, int len)方法
* 复制成功无乱码
*/
public static void fileCopy3() throws Exception {
FileInputStream in = new FileInputStream("D:/a.txt");
FileOutputStream out = new FileOutputStream("D:/b.txt");
byte[] buffer = new byte[1024];
int length = 0;
while ((length= in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
System.out.println("copy完成");
in.close();
out.close();
}
经过几个方法的测试发现,出现乱码主要是出现在write方法。
对比发现,通过read(byte[] b)进行读取的时候,每次读取的字节长度为1024,如果存在读取的字节长度不够1024,write(byte[] b)每次写入字节长度依然是1024,所以可能出现乱码等情况出现。而write(byte[] b, int off, int len)方法,每次写入的是字节数组中的实际字节长度,所以没有乱码问题。