【问题标题】:Cannot move csv file from one directory to other无法将 csv 文件从一个目录移动到另一个目录
【发布时间】:2014-12-04 00:15:18
【问题描述】:

我试图在读取 csv 文件的内容并将其存储在数据库中后对其进行存档。我是这样做的

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

其中文件 =“D:\Users\400220260.INDCORP\Desktop\ParameterMargin20141009.csv”
和目的地 = "D:\Users\400220260.INDCORP\Desktop\Archive\ParameterMargin20141009.csv"

请帮忙 提前致谢

【问题讨论】:

  • 让我们看看一些代码
  • 我忘记关闭文件对象中的 FileReader。它现在工作正常。

标签: java file archive


【解决方案1】:

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

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 Commons IO 的 FileUtils 的 copyFile 方法会更简单,但您必须在项目中添加该库:

FileUtils.copyFile(File srcFile, File destFile)

【讨论】:

  • 我必须移动它工作正常的文件,但它正在将文件从一个位置复制到另一个位置
  • 可以使用file.delete()删除第一个文件
【解决方案2】:

正如Javadoc中所述:

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

您可以使用java.nio.file 中的Files.copy(InputStream in, Path target, CopyOption... options) 来实现此目的。

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2017-07-20
    • 2014-07-18
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2016-06-09
    相关资源
    最近更新 更多