【发布时间】:2018-03-09 00:26:02
【问题描述】:
我必须将文件从一个目录移动到另一个目录。
我正在使用属性文件。因此源和目标路径存储在属性文件中。 我也有属性阅读器类。
在我的源目录中有很多文件。如果完成操作,一个文件应该移动到另一个目录。
文件大小超过 500MB。
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
我的代码没有将文件移动到正确的路径。
这是我的属性文件
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
文件应该在 B 盘。怎么做?任何人都可以帮助我..!!
【问题讨论】:
-
FileChannel.transferTo()可能是您需要的。 -
我认为您的目录应该以
"\"结尾。这样dir + file.getName()会产生一个有效的路径。 -
在您提供的代码中确保 secondarydir 以“\”结尾。如果是primarydir,则不需要。
-
File.rename()在 linux 上源/目标路径位于不同分区时将不起作用,因此它可能在 Windows 上也不起作用,您需要检查boolean返回值以了解是否成功与否。