【问题标题】:Appending "Copy" before extension of filename when copying files复制文件时在文件扩展名前附加“复制”
【发布时间】:2012-03-22 17:52:18
【问题描述】:

假设源文件名为Foo.txt。我希望目标文件的名称为Foo(Copy).txt。我希望保留源文件。我该怎么做呢?

/*
 * Returns a copy of the specified source file
 * 
 * @param sourceFile the specified source file
 * @throws IOException if unable to copy the specified source file
 */
public static final File copyFile(final File sourceFile) throws IOException 
{
    // Construct the destination file
    final File destinationFile = .. // TODO: Create copy file
    if(!destinationFile.exists()) 
    {
        destinationFile.createNewFile();
    }

    // Copy the content of the source file into the destination file
    FileChannel source = null;
    FileChannel destination = null;
    try 
    {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destinationFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    }
    finally 
    {
        if(source != null) 
        {
            source.close();
        }
        if(destination != null) 
        {
            destination.close();
        }
    }

    return destinationFile;
}

【问题讨论】:

  • 除了像懂事的人一样使用 Commons IO FileUtils
  • 另一种方便的方法是使用 Ant CopyTask:docjar.com/html/api/org/apache/tools/ant/taskdefs/…
  • 为什么 skaffman 的评论没有必要或我错过了什么?
  • 这不是冷嘲热讽(至少,它不是故意的)。在我看来,手工编写这类东西是愚蠢的,除非有充分的理由不能使用 Commons IO。
  • @mre 我几乎不会把 skaffman 的评论称为讽刺。更能说明问题的是,您已经在这个网站上工作了一年多,拥有 13k+ 的声誉,积极参与 Java 问题,并且在将这个问题发布到网站上之前,没有想过要查看 Apache Commons 以了解毫无疑问的常见任务。在我看来

标签: java file copy


【解决方案1】:

我会这样做:

String name = sourceFile.getName();
int i = name.contains(".") ? name.lastIndexOf('.') : name.length();
String dstName = name.substring(0, i) + "(Copy)" + name.substring(i);
File dest = new File(sourceFile.getParent(), dstName);

【讨论】:

  • @ZackMacomber,应该是sourceFile。固定。
【解决方案2】:

Google 的 Guava 库中有一个方便的方法Files.copy(File, File)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2014-06-12
    • 2023-01-24
    • 1970-01-01
    相关资源
    最近更新 更多