注意: 字符流只能处理文本文件,字节流可以处理非文本文件,也可复制文本文件的复制,其他操作可能会出现乱码。
说明:
文本文件:.txt、.java、.c、.cpp、.py等
非文本文件:.doc、.xls、.jpg、.pdf、.mp3、.mp4、.avi 等
File file = new File("face.png");
File newFile = new File("face_copy.png");
FileInputStream fis=new FileInputStream(file);
FileOutputStream fos=new FileOutputStream(newFile);
byte[] cBuffer = new byte[5];
int len;
while((len=fis.read(cBuffer))!=-1){
fos.write(cBuffer);
}
fos.close();
fis.close();
/**
* 需求复制face.png为face_copy.png
*/
@Test
public void test01(){
File file =null;
File newFile=null;
FileInputStream fis=null;
FileOutputStream fos=null;
try {
file = new File("face.png");
newFile = new File("face_copy.png");
fis = new FileInputStream(file);
fos = new FileOutputStream(newFile);
byte[] cBuffer = new byte[5];
int len;
while((len=fis.read(cBuffer))!=-1){
fos.write(cBuffer);
}
System.out.println("复制成功");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (fos!=null){
fos.close();
}
if (fis!=null){
fis.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
推荐阅读: