Reputation: 13254
I have a JFilechooser to select a filename and path to store some data. But I also want to store an additional file in the same path, same name but different extension. So:
File file = filechooser.getSelectedFile();
String path = file.getParent();
String filename1 = file.getName();
// Check the extension .ext1 has been added, else add it
if(!filename1.endswith(".ext1")){
filename2 = filename1 + ".ext2";
filename1 += ".ext1";
}
else{
filename2 = filename1;
filename2 = filename2.substring(0, filename2.length-4) + "ext2";
}
// And now, if I want the full path for these files:
System.out.println(path); // E.g. prints "/home/test" withtout the ending slash
System.out.println(path + filename1); // E.g. prints "/home/testfilename1.ext1"
Of course I could add the "/" in the middle of the two strings, but I want it to be platform independent, and in Windows it should be "\" (even if a Windows path file C:\users\test/filename1.ext1 would probably work).
I can think of many dirty ways of doing this which would make the python developer I'm carrying inside cry, but which one would be the most clean and fancy one?
Upvotes: 1
Views: 110
Reputation: 36329
Just use the File class:
System.out.println(new File(file.getParent(), "filename1"));
Upvotes: 1
Reputation: 51343
You can use the constants in the File class:
File.separator // e.g. / or \
File.pathSeparator // e.g. : or ;
or for your path + filename1
you can do
File file = new File(path, filename1);
System.out.println(file);
Upvotes: 3