Ann Pera Ann Pera - 1 year ago 90
Java Question

Java saving file under same name in same directory with different extension

I'm writing a very basic java program that takes a file, does some modifications and saves the output in a different file. My problem is that I would like to save it under the same name, but with a different extension.

My current code gets the original file using the JFileChooser, converts it to a path, and uses the .resolveSibling() method. This, however, will result in test.ngc's output being saved in test.ngc.fnc

Is there any good way to save a file under the same name, but with a diffrent extension as the one selected?

Path originalFile = null;

JFileChooser chooser = new JFileChooser(".ngc");
chooser.setFileFilter(new FileNameExtensionFilter("Pycam G Code files", "ngc"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
originalFile = chooser.getSelectedFile().toPath();

Path newFile = originalFile.resolveSibling(originalFile.getFileName() + ".fnc");

/* does reading and modification and saving here using BufferedReader and BufferedWriter*/

Answer Source

This should work:

String originalFilename = originalFile.getFileName();
String fileNameNew = originalFilename.substring(0, originalFilename.length()-".ngc".length())+".fnc";
Path newFile = originalFile.resolveSibling(fileNameNew);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download