1

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.

Thanks in advance.

1

3 Answers 3

1

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.

Checking the existence of the file with File.exists() in a loop does not give you such guarantee.

Sign up to request clarification or add additional context in comments.

Comments

0

if you can persist the number of uploads you could increment a number for each particular file and attend it to your filename (e.g. foo_1.txt or however you want) if you can't you might wanna go through all your files and check if they fit your naming schema. then you can extract the highest number, increment it by 1 and append it to your new file.

Comments

0

check the methods of File like:

exists()

if the file is existing you can count a number and create a new file name like

newFilename = MessageFormat.format("({0}){1}", counter++, originalFilename);
File newFile = new File(originalFile.getParentFile(),newFilename);

You can create and check new files as long as you find a filename which is not existing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.