Reputation: 23
I need to rename an .afp
file with name of .txt
file. I have stumbled across numerous "solutions" while trying to get this thing working and nothing helped.
Let's say I have a txt file in C:/test/a/Mytes t.txt
and I want to rename .afp
file which is in C:/files/b/Testf ile.afp
. This is what I'm trying to do (according to solutions found on this site) and it isn't working. I cut the extension of .txt
file and get only file name:
String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
//fileName is .txt file name
File file = new File(afpSRC, afpName);
file.renameTo(new File(afpSRC, fileNameNoExt + ".afp"));
afpSRC
contains Path to folder in which .afp
file is located and afpName
is the name of the file.
Can anyone tell me why this isn't working and .afp
file name remains the same?
Upvotes: 1
Views: 123
Reputation: 11631
If you use the Java NIO facilities, you will be able to get information through an exception explaining why the rename has failed.
Files.move(Path from, Path to, CopyOption... options) throws IOException
String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
Path afpPathName = Paths.get(afpSRC, afpName);
Path newPathName = Paths.get(afpSRC, fileNameNoExt + ".afp");
Files.move(afpPathName, newPathName);
Upvotes: 1
Reputation: 131396
Probably because File file = new File(afpSRC, afpName);
doesn't refer a existing file.
I suspect that either afpSRC
is not the parent path or afpName
is not the filename. Or both ?
To debug you should check that the file exists first.
If it doesn't exist, throw an exception.
Besides in any way (debug and final code) you should check the returned value by renameTo()
and handle it consequently.
Here is a sample code :
String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
//fileName is .txt file name
File file = new File(afpSRC, afpName);
if (!file.exists()){
throw new RuntimeException("file not found = " + file);
}
boolean isRenamed = file.renameTo(new File(afpSRC, fileNameNoExt + ".afp"));
System.out.println("isRenamed = " + isRenamed);
if (!isRenamed){
// handle the problem
}
Upvotes: 0