我必须将文件从一个目录移动到另一目录。
我正在使用属性文件。因此,源路径和目标路径存储在属性文件中。我也有物业阅读器类。
在我的源目录中,有很多文件。如果一个文件完成了操作,则应将其移动到其他目录。
文件大小超过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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的代码未将文件移动到正确的路径。
这是我的财产文件
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Run Code Online (Sandbox Code Playgroud)
文件应位于B驱动器中。怎么做?任何人都可以帮助我.. !!
更改此:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
Run Code Online (Sandbox Code Playgroud)
对此:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
Run Code Online (Sandbox Code Playgroud)
最好不要使用字符串连接来连接路径段,因为正确的方法可能取决于平台。
编辑:如果可以使用JDK 1.7 API,则可以使用Files.move()
代替File.renameTo()