【问题标题】:Java File Copy -How to Backup/copy the input file to other destination location?Java 文件复制 - 如何将输入文件备份/复制到其他目标位置?
【发布时间】:2020-01-09 19:51:54
【问题描述】:

想要在执行之前将文件复制/备份到目标文件夹 任何任务。 (jdk -1.7)


 /*Input file path taken from properties file as string is :inputFile
where-in inputFile is :C:\\Project\\input\\filename.txt
Destination file path taken from properties file as string is : 
archiveFolderPath */

  //Existing code : in main
if (inputFile != null) {
readTextFile(new File(inputFile)); }

// in readTextFile method
BufferedReader br = new BufferedReader(new FileReader(filename));

我尝试使用以下过程:: 但出现错误: 错误:: Files 类型中的方法 copy(InputStream, OutputStream) 不是 适用于参数(字符串,字符串)

//Calling method in main::
copyFiles(inputFile, archiveFolderPath);


//Copy method :
private static void copyFiles (String inputFile, String 
  archiveFolderPath) throws IOException {
    Files.copy(inputFile, archiveFolderPath); }

请提出替代解决方案,因为“文件不适用于 参数(字符串,字符串)”。

【问题讨论】:

  • 我认为错误消息非常解释 - 你不能将 String 传递给方法,你必须传递 InputStream (这是源代码)和 OutputStream (这是目的地)。这是基本的 I/O 处理。您还需要考虑 String 含义较少并且可能意味着许多不同的东西的概念,因此 API 迫使您先做一些准备工作,使其更灵活,更少歧义,更容易应用于不同的情况
  • 我“建议”您首先查看Basic I/O 并咨询JavaDocs for the Files API

标签: java bufferedreader filereader file-copying


【解决方案1】:

您可以在对文件执行读取或写入操作之前复制文件。示例:-

Path origin = Paths.get("/home/fm/source.txt");
Path destination = Paths.get("/home/fm/source.bak");

//Copy source.txt to source.bak
Files.copy(origin, destination, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);

有关所有copy 方法的详细信息,请参阅Files javadoc。他们中的一些人期望CopyOption 作为参数。根据节目要求选择合适的CopyOption

https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardCopyOption.html#COPY_ATTRIBUTES

【讨论】:

  • 需要注意的是,不能将目录传递给Files.copy。作为the documentation suggests,需要将目录解析为文件名,例如Files.copy(inputPath, archivePath.resolve(inputPath.getFileName()), …)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 2015-07-01
  • 1970-01-01
  • 2023-01-13
相关资源
最近更新 更多