如何使用java在同一目录中创建具有相同名称的多个文件? [英] how can create multiple files with same name in the same directory using java?
问题描述
根据我的要求,我需要将文件上传到指定的目录,稍后经过一些修改,我需要将同一个文件上传到同一个目录,这里以前的文件不应该被覆盖,这意味着文件必须保存在同名目录(这里我有一个假设,例如,如果我的文件是abc.txt,修改后,如果我上传修改的文件,它可以保存为abc(1).txt)。我如何解决我的问题?任何人都可以帮助我从这个问题中脱颖而出。
As per my requirement,i need to upload a file into a specified directory,later after some modifications, i need to upload the same file into the same directory,here previous file should not be overridden means files must be saved in the same directory with same names(here i have one assumption,that , for example if my file is abc.txt, after modifications if i upload the modified file it can be saved as abc(1).txt ). how can i resolve my issue? can anybody assist me to come out from this issue.
提前感谢。
推荐答案
使用 File.createNewFile()
。当且仅当该文件不存在时,它将创建文件。这是线程安全的,因为API保证原子性。
Use File.createNewFile()
in a while loop. It will create the file if and only if the file does not exist. This is thread-safe, since the API guarantees atomicity.
使用 File.exists()
一个循环不给你这样的保证。
Checking the existence of the file with File.exists()
in a loop does not give you such guarantee.
这篇关于如何使用java在同一目录中创建具有相同名称的多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!