复制
@Test
public void FileCopy() {
String fromPath = "E:\\IO_CopyFrom\\alan.txt";
String toPath = "E:\\IO_CopyTo\\alan.txt";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(fromPath);
fileOutputStream = new FileOutputStream(toPath);
//定义一个字节数组提高读取效率
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1) {
//读取到字节数据后马上进行写入
//一定要使用(byte[] b,int off,int len) 因为数据总字节数未必可以被字节数组容量整除
fileOutputStream.write(buf, 0, readLen);
}
System.out.println("复制完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
剪切
实质上在复制的基础上将原文件删除,即为剪切
注:删除命令需要在流关闭后使用,否则文件处于被占用状态,无法进行删除
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//在复制完成后进行原文件删除 即为剪切
//删除命令需要在流关闭后使用 否则文件处于被占用状态 无法进行删除
del();
}
@Test
public void del() {
String filePath = "E:\\IO_CopyFrom\\alan.txt";
File file = new File(filePath);
file.delete();
}
}