一、采用流来处理文件的移动,这样会导致有两份文件需要删除
//fileSourcePath源文件路径 fileTargetPath目标文件路径
File file = new File(fileSourcePath);
String targetDirPath = fileTargetPath.substring(0, fileTargetPath.lastIndexOf("/"));
Path targetDir = Paths.get(targetDirPath);
// 如果目标文件夹不存在,则创建它
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
File file1 = new File(fileTargetPath);
byte[] bytes = Files.readAllBytes(file.toPath());
FileOutputStream outputStream = new FileOutputStream(file1);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
try {
file.delete();
}catch (Exception e){
}
二、采用java.nio.file中的Files中的copy方法,有两份文件需要删除
try {
//fileSourcePath源文件路径 fileTargetPath目标文件路径
Path sourcePath = Paths.get(fileSourcePath);
String targetDirPath = fileTargetPath.substring(0, fileTargetPath.lastIndexOf("/"));
Path targetDir = Paths.get(targetDirPath);
Path targetPath = Paths.get(fileTargetPath);
// 如果目标文件夹不存在,则创建它
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
// 移动文件,如果目标文件已存在,则替换它
Files.copy(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);
try {
//文件执行拷贝时间需要等待,不然无法删除源文件
File file = new File(fileSourcePath);
file.delete();
}catch (Exception e){
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.out.println("移动图片时出现错误");
}
三、采用java.nio.file中的Files中的remove方法,不需要删除,但是源文件不能
处于使用状态,不然或出现异常;
try {
Path sourcePath = Paths.get(fileSourcePath);
String targetDirPath = fileTargetPath.substring(0, fileTargetPath.lastIndexOf("/"));
Path targetDir = Paths.get(targetDirPath);
Path targetPath = Paths.get(fileTargetPath);
// 如果目标文件夹不存在,则创建它
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
// 移动文件,如果目标文件已存在,则替换它
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
System.out.println("移动图片时出现错误");
}
以上就是我目前知道的三种方式,不足之处,还望勿怪;