Results 1 to 6 of 6
- 01-21-2010, 06:43 AM #1
Member
- Join Date
- Aug 2009
- Posts
- 48
- Rep Power
- 0
How to check file existence and rename file with little modification
Hi,
Hope you all will be fine. I want to ask i created a file named msg0000.wav in a directory named 220. Now i want to check if msg0000.wav already exist in the director then make a new file but with name msg0001.wav in the same directory and after reaching to number 9(msg0009.wav) it becomes msg0010.wav, msg0011.wav and so on. Means each time it check file exist or not and if file exist then simply change the number as i mentioned above.
Please guide me how can i do it. Checking file is easy i know it is do by a method "exist()" like file.exist() but how can i implement this logic that increment number each time if file exist.
Thank you.
- 01-21-2010, 09:40 AM #2
Java Code:/*Please go thru the code sample*/ import java.io.*; class Test { public static void main(String[] args) throws Exception { //Initially file trial.txt is there in the directory File f = new File("trial.txt"); int i=0; while( i < 6) { if(f.exists()) { f = new File("trial"+i); f.createNewFile(); i++; } }//while }//main }//TestRamya:cool:
- 01-21-2010, 09:45 AM #3gcampton Guest
i think you meant to put:
if(! f.exists())
- 01-21-2010, 09:46 AM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,476
- Rep Power
- 16
Substring the pre-. filename (msg0001) so you grab the last 4 characters, and turn that into an int. Increment that int. String.format() that against a format which will insert a padded number inbetween msg and .wav.
Of course, this will involve reading every filename in the directory to find the largest id. Better would be to keep track of the last used id (or the next id, possibly) and completely skip the substringing part.
- 10-17-2012, 07:40 AM #5
Member
- Join Date
- Oct 2012
- Posts
- 1
- Rep Power
- 0
Re: How to check file existence and rename file with little modification
How do you do this with a directory though. So if the directory "folder name" already exists then create a new folder and incriment the name as such. Folder. Folder_1. Folder_2
- 10-17-2012, 10:07 AM #6
Moderator
- Join Date
- Apr 2009
- Posts
- 10,476
- Rep Power
- 16
Similar Threads
-
Unbale to delete and rename file
By ddatta8 in forum New To JavaReplies: 0Last Post: 01-31-2009, 01:16 PM -
How to check whether file is exists or not
By Java Tip in forum java.ioReplies: 0Last Post: 04-05-2008, 10:13 AM -
How to rename a file
By Java Tip in forum java.ioReplies: 0Last Post: 04-05-2008, 10:11 AM -
How to change the date of modification of a file
By Java Tip in forum java.ioReplies: 0Last Post: 04-05-2008, 10:10 AM -
How to Rename a File
By Ada in forum New To JavaReplies: 1Last Post: 05-26-2007, 12:55 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks