【发布时间】:2015-12-30 06:02:07
【问题描述】:
我正在尝试将文件从一个目录移动到另一个目录,在移动后从源目录中删除该文件。
for (File file : files) {
if (file != null) {
boolean status = moveFile(file, filePath, name, docGroupId);
if (status) {
//some operations....
}
}
}
public static boolean moveFile(final File file, final String filePath, final String groupName, Integer docGroupId) {
// TODO Auto-generated method stub
String selectedDirectory = filePath + File.separator + groupName;
InputStream in = null;
OutputStream out = null;
try {
if (!file.isDirectory()) {
File dir = new File(selectedDirectory);
if (!dir.exists()) {
dir.mkdirs();
}
String newFilString = dir.getAbsolutePath() +
File.separator + file.getName();
File newFile = new File(newFilString);
in = new FileInputStream(file);
out = new FileOutputStream(newFile);
byte[] moveBuff = new byte[1024];
int butesRead;
while ((butesRead = in.read(moveBuff)) > 0) {
out.write(moveBuff, 0, butesRead);
}
}
in.close();
out.close();
if(file.delete())
return true;
} catch (Exception e) {
return false;
}
}
程序在Linux-Ubuntu 上运行,所有文件都被移动到另一个目录并从源目录中删除,但在Windows 系统中,所有文件都被移动但未能从源目录中删除一两个文件。请注意,在调试程序时运行正常。
【问题讨论】:
-
使用可以使用apache io函数org.apache.commons.io.FileUtils.moveDirectory(srcDir, destDir);
-
有什么错误吗?你应该在 catch 块中打印异常
-
我不想移动目录中的所有文件。只移动选定的文件
-
然后使用moveFile函数或者moveFileToDirectory(srcFile, destDir, createDestDir);
-
您正在吃掉异常,在 catch 块中没有记录/打印任何内容。你怎么确定你没有收到任何错误