【问题标题】:Copy file1 name inplace of file2 and add extra to it, but not copy file1 extention复制 file1 名称代替 file2 并添加额外内容,但不复制 file1 扩展名
【发布时间】:2015-08-03 03:15:26
【问题描述】:

如何更改文件名以匹配原始文件并在其中包含额外的txt,请参见下面的示例

原创 数据文件.txt thisNameNeedsToMatchDataFile.txt(但在 .txt 之前还添加了“.Step2”)

期望的输出 数据文件.txt 数据文件.Step2.txt

任何帮助都将被占用,谢谢你。

【问题讨论】:

  • 你的问题不完全清楚
  • 抱歉,我有两个文件,file1 和 file2,我需要从 file1 复制名称来代替我的 file2 名称,但是当它正在将 file1 名称复制到 file2 时,我需要添加附加 txt到file2的名称,所以最后例如file1应该看起来像datafile.txt,file2应该看起来像datafile.Step2.txt。对不起,我又不够清楚。
  • 仍然不清楚..请用给定的输入、文件..和所需的输出来扩展您的问题..一步一步..不要把整个“逻辑”放在一个句子中
  • 更重要的是,您自己尝试了什么?
  • 你能告诉我们你到目前为止所做的尝试吗?

标签: java file copy filenames rename


【解决方案1】:

我如何理解您的问题这是我认为解决方案的样子 (java 7+)

public class FileConverter {

public static void main(String[] args) throws IOException {
    FileConverter converter = new FileConverter();
    File newFile1 = new File("c:/parent1/file1.dump");
    File newFile2 = new File("c:/parent2/file2.dump");
    converter.convert2Files(newFile1, newFile2);
}

private void convert2Files(File file1, File file2) throws IOException {
    // compare if the 2 files have the same name
    if(file1.getName().equalsIgnoreCase(file2.getName())){
        String newName = file1.getName().substring(0, file1.getName().lastIndexOf('.')); 
        String newNameOriginal = newName + ".txt";
        String newNameStep2 = newName + ".Step2.txt";
        File newFileOriginal = new File(file1.getParent(),newNameOriginal);
        File newFileStep2 = new File(file1.getParent(),newNameStep2);
        Path file = file1.toPath();/* use file1 as source file */
        Path to = Paths.get(file1.getParent());/* path to destination directory */
        Files.copy(file, to.resolve(newFileOriginal.toPath()));
        Files.copy(file, to.resolve(newFileStep2.toPath()));
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2015-01-17
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多