【发布时间】:2014-05-28 12:10:30
【问题描述】:
如何在java中使用将文件从一个目录移动到另一个目录?请让我知道是否有任何替代解决方案可以在 java 中执行此操作。
public class FileTransform
{
public static void copyFile(File sourceFile, File destFile) throws IOException
{
if (!destFile.exists())
{
destFile.createNewFile();
}
System.out.println("Copy File Method");
FileChannel source = null;
FileChannel destination = null;
try
{
source = new FileInputStream(sourceFile).getChannel();
System.out.println("Destination File :"+destFile);
destination = new FileOutputStream(destFile).getChannel();
// previous code: destination.transferFrom(source, 0, source.size());
// to avoid infinite loops, should be:
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size - count)) < size);
}
finally
{
if (source != null)
{
source.close();
}
if (destination != null)
{
destination.close();
}
}
}
public static void main(String[] args) throws IOException
{
FileTransform ft = new FileTransform();
File src= new File("C:/File/File1/A10301A0003174228I_20140528080958095/A10301A0003174228I.xml");
File dest= new File("E:/FileDest/File1");
ft.copyFile(src,dest);
}
}
上面的代码我得到异常是
Exception in thread "main" java.io.FileNotFoundException: E:\FileDest\File1 (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at FileTransform.copyFile(FileTransform.java:22)
at FileTransform.main(FileTransform.java:48)
我收到 File not found 异常,请告诉我如何在 java 中执行此操作
【问题讨论】:
-
嗯,错误信息很清楚为什么会抛出异常。
-
异常显示“访问被拒绝”。你对“E:\FileDest\”有写权限吗?
-
您似乎没有权限将文件写入E:\驱动器或E:\不存在。