文件复制
使用FileInputStream + FileOutputStream完成文件的拷贝。
拷贝的过程应该是一边读一边写
核心代码:
while ((readcount = fis.read(bytes))!=-1){
fos.write(bytes,0,readcount);
}
-
使用以上的字节流拷贝文件时,文件类型随意,万能的,什么样的文件都能拷贝。
-
关闭流时,分开try,不要一起try。
一起try的时候,如果其中一个出现异常,可能会影响另一个流的关闭。
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("C:\\Users\\ThinkPad\\Pictures\\爱壁纸UWP\\城市\\城市_1.jpg");
fos = new FileOutputStream("C:\\Users\\ThinkPad\\Pictures\\爱壁纸UWP\\视觉\\城市_1.jpg");
int readcount = 0;
byte[]bytes = new byte[1024*1024];//一次最多拷贝1mb
while ((readcount = fis.read(bytes))!=-1){
fos.write(bytes,0,readcount);
}
fos.flush();
或者:
不能用于大文件
byte[]bytes = new byte[fis.available()];
fis.read(bytes);
fos.write(bytes);
分开try
finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}