[英]Generate filename for a copied file
I am looking to get similar behaviour to what you get in Windows when you copy and paste a file in the same directory. 当您将文件复制并粘贴到同一目录中时,我希望获得与Windows相似的行为。
For eg, if you've copy/paste a file called foo.txt
, it will create foo Copy.txt
and if you paste it once more, it creates foo Copy(2).txt
and if you copy/paste foo Copy.txt
, foo Copy Copy.txt
is created. 例如,如果您复制/粘贴了一个名为
foo.txt
的文件,它将创建foo Copy.txt
,如果再次粘贴,它将创建foo Copy(2).txt
并且如果您复制/粘贴foo Copy.txt
,创建foo Copy Copy.txt
。
Is there a Java utility function that does this? 有执行此操作的Java实用程序功能吗? I've looked at
File.createTempFile
but the filename it generates is too long and contains a UID-like substring. 我看过
File.createTempFile
但是它生成的文件名太长,并且包含类似UID的子字符串。
通过将FileChooser与“ showSaveDialog”方法结合使用,您将获得所需的结果,因为Java随后将OS行为用于现有文件。
Sometimes, you just have to do the work first, it will give you an appreciation for the API. 有时,您只需要首先进行工作即可,它将使您对API有所了解。 Then you can write your own utility methods
然后,您可以编写自己的实用程序方法
File original = new File("build.xml");
String path = original.getAbsoluteFile().getParent();
String name = original.getName();
String ext = name.substring(name.indexOf("."));
name = name.substring(0, name.indexOf("."));
name = path + File.separator + name;
int index = 1;
File copy = new File(name + " (" + index + ")" + ext);
while (copy.exists()) {
index++;
copy = new File(name + " (" + index + ")" + ext);
}
System.out.println(copy);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.