无法将csv文件从一个目录移动到另一个目录

问题描述:

我想在读取其内容并将其存储在数据库中之后将csv文件存档。我这样做是无法将csv文件从一个目录移动到另一个目录

String filename = file.getName(); 
File destiantion = new File(getAttribute(ST_ARCHIVE_FOLDER) + "/"+ filename); 
boolean fileArchived = file.renameTo(destiantion); 

其中file = “d:\用户\ 400220260.INDCORP \桌面\ ParameterMargin20141009.csv”
和目标=“d:\用户\ 400220260.INDCORP \桌面\存档\ ParameterMargin20141009.csv”

请帮助 在此先感谢

+0

让我们看看一些代码 – 2014-10-09 06:59:46

+0

我忘记关闭我的文件对象中的FileReader。它的工作现在很好。 – Gurpaldeep 2014-10-10 12:26:00

你有你的文件的对象,但现在你必须将旧文件复制到新的位置。只需重命名文件就不会做你想要的。这是可以做到这样的:

public static void copyFile(File sourceFile, File destFile) throws IOException { 
    destFile.createNewFile(); 
    FileChannel source = null; 
    FileChannel destination = null; 

    try { 
     source = new FileInputStream(sourceFile).getChannel(); 
     destination = new FileOutputStream(destFile).getChannel(); 
     destination.transferFrom(source, 0, source.size()); 
    } 
    finally { 
     if(source != null) { 
     source.close(); 
     } 
     if(destination != null) { 
     destination.close(); 
     } 
    } 
} 

什么会更容易使用Apache的共享IO文件实用程序的的CopyFile方法,但因此,你必须添加该库在您的项目是:

FileUtils.copyFile(File srcFile, File destFile) 
+0

我必须移动它正在工作的文件,但它正在将文件从一个位置复制到另一个位置 – Gurpaldeep 2014-10-09 07:20:39

+0

您可以使用file.delete()删除第一个文件, – 2014-10-09 07:23:16

由于它在Javadoc说:

The rename operation might not be able to move a file from one filesystem to another. 

你可以使用Files.copy(InputStream in, Path target, CopyOption... options)java.nio.file实现这一目标。