gpt4 book ai didi

java - 复制文件时在文件扩展名前附加 "Copy"

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:02 26 4
gpt4 key购买 nike

假设源文件名为 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;
}

最佳答案

这是我的做法:

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);

关于java - 复制文件时在文件扩展名前附加 "Copy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9827808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com