利用IO流中的FileInputStream和FileOutputStream来实现读写操作
FileInputStream和FileOutputStream是字节流,与FileReader和FileWriter不同。它的缓冲数组为byte类型的,可以处理非文本文件和文本文件,但是在处理文本文件的时候不能显示在控制台中(如果文本文件中有中文字符或其他特殊字符的话,因为会受到byte数组大小的影响从而会导致字符被分割开出现乱码)
如果复制这个更改后的hello文件,在控制台输出会出现乱码
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author LTH
* @date 2021/4/4 - 9:36
*/
public class FileInputStreamOutputStream {
@Test
public void testFileInputOutputStream() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File("pic.png");
File destFile = new File("pic2.png");
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//复制的过程
byte[] buffer = new byte[5];
int len;
while ((len = fis.read(buffer)) != -1){
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}