java - How to sequentially numbering files rather than overwriting them when moving -
i writing code move file 1 directory another, have issue having file have same name, decided number them don't want overwrite them.
assume have file a.txt, succeed move move file same name call a_1.txt, wondering can if have again a.txt?
moreover, feel code not efficient , appreciated if me enhance it.
my code is:
/* * method move specific file directory */ public static void movefile(string source, string destination) { file file = new file(source); string newfilepath = destination + "\\" + file.getname(); file newfile = new file(newfilepath); if (!newfile.exists()) { file.renameto(new file(newfilepath)); } else { string filename = filenameutils.removeextension(file.getname()); string extention = filenameutils.getextension(file.getpath()); system.out.println(filename); if (isnumeric(filename.substring(filename.length() - 1))) { int filenum = integer.parseint(filename.substring(filename.length() - 1)); file.renameto(new file(destination + "\\" + filename + ++filenum + "." + extention)); } else { file.renameto(new file(destination + "\\" + filename + "_1." + extention)); } }//end else }
from main, called following (note managefiles class name method exist in):
string source = "l:\\test1\\graduate.jpg"; string destination = "l:\\test2"; managefiles.movefile(source, destination);
you can use logic:
if file exists in destination, add "(1)" file name (before extension). ask me: if there's file "(1)"? use (2). if there's 1 (2) too, use (3), , on.
you can use loop acomplish this:
/* * method move specific file directory */ public static void movefile(string source, string destination) { file file = new file(source); string newfilepath = destination + "\\" + file.getname(); file newfile = new file(newfilepath); string filename; string extention; int filenum; int cont; if (!newfile.exists()) { file.renameto(new file(newfilepath)); } else { cont = 1; while(newfile.exists()) { filename = filenameutils.removeextension(file.getname()); extention = filenameutils.getextension(file.getpath()); system.out.println(filename); newfile = new file(destination + "\\" + filename + "(" + cont++ + ")" + extention); } newfile.createnewfile(); }//end else }
Comments
Post a Comment