I'm trying to save a file using JFileChooser. However, I seem to be having some trouble with it. Here's my code:
if (e.getSource() == saveMenu) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
// add filters
chooser.addChoosableFileFilter(xmlFilter);
chooser.setFileFilter(xmlFilter);
int result = chooser.showSaveDialog(Simulation.this);
if (result == chooser.APPROVE_OPTION) {
writeToXML(chooser.getSelectedFile());
}
}
This doesn't force the file to have a .xml extension, so I've tried to use the following code to force the file to be saved with the extension .xml
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter xmlWriter = null;
try {
xmlWriter = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(f+".xml"), "UTF8"),
format);
However, with this I can't prevent the user from writing xpto.xml in the JFileChooser and if they do that, the file will have "two extensions": it will be a file named xpto.xml.xml
So my questions are:
How can I make the JFileChooser save an xml file by default?
If the user inserts a file name like xpto.xml, how can I save it as xpto.xml and not xpto.xml.xml?
As you've noticed, JFileChooser doesn't enforce the FileFilter on a save. It will grey-out the existing non-XML file in the dialog it displays, but that's it. To enforce the filename, you have to do all the work. (This isn't just a matter of JFileChooser sucking -- it's a complex problem to deal with. Your might want your users to be able to name their files xml.xml.xml.xml.)
In your case, I recommend using FilenameUtils from Commons IO:
File file = chooser.getSelectedFile();
if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("xml")) {
// filename is OK as-is
} else {
file = new File(file.toString() + ".xml"); // append .xml if "foo.jpg.xml" is OK
file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".xml"); // ALTERNATIVELY: remove the extension (if any) and replace it with ".xml"
}
There's also some ideas for what to do if you want multiple types in the save dialog here: How to save file using JFileChooser?
Just to make things clear as to how to use the JFileChooser to save files.
//set it to be a save dialog
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
//set a default filename (this is where you default extension first comes in)
chooser.setSelectedFile(new File("myfile.xml"));
//Set an extension filter, so the user sees other XML files
chooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));
now the user was encouraged to save the item as an xml file in this example, but they may not have actually set it.
if(chooser.showSaveDialog(this) == jFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().toString();
if (!filename .endsWith(".xml"))
filename += ".xml";
//DO something with filename
}
This is the most simple case, if you have multiple possible file formats, then you should catch the selected filter, verify THAT extension, and also save the file according to the selected format. but if you are doing that, you are probably an advanced java programmer and not utilizing this post.
How about something like this:
else if (e.getSource() == saveMenu) {
int returnVal = chooser.showSaveDialog(Simulator.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String fname = file.getAbsolutePath();
if(!fname.endsWith(".xml") ) {
file = new File(fname + ".xml");
if(!file.createNewFile()) {
/*check with user??*/
}
You should try this:
if(!file.getName().contains(".")) file = new File(file.toString() + ".xml");
You should try this. I did this and it worked.
FileOutputStream fileOut = new FileOutputStream(file1+".xml");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
Related
i got a problem with my code. First of all, i created a JfileChooser, to save my bufferedImage into a file.
The problem is when i save it, if i don't write the extension in the window it will be a normal file instead of a jpg/png or other.. How can i do that?
I tryed some weird code like getting the description of fileextension but it doesn't work
JFileChooser savechooser = new JFileChooser();
savechooser.setFileFilter(new FileNameExtensionFilter("JPEG File", "jpg"));
savechooser.setFileFilter(new FileNameExtensionFilter("PNG File", "png"));
savechooser.setFileFilter(new FileNameExtensionFilter("GIF File", "gif"));
int returnVal = savechooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
ImageIO.write(bImage, "png" , new File(savechooser.getSelectedFile().getAbsolutePath()));
I expect a "test.png" or "test.jpeg", but the actual output would be a "test" file..
The second parameter to ImageIO.write(...) ("png" in your code) is the format of the file. This is not directly related to the name of the file. A "file extension" or suffix is simply part of the name of a file, and may be anything, although by convention it is used to indicate the format of the file (ie. nothing stops you from naming a JPEG file "foo.gif" if you really want to, and it is still a JPEG file). Windows typically uses this convention to determine file type and select the appropriate application to open the file though, so using a non-standard extension may be confusing.
To fix the the problem you see, it's probably best to make sure that filename ends with the correct extension, unless the user added one. For example (assumes the user chose PNG format, but you can easily adapt it to other formats as well):
// JFileChooser code as is
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = savechooser.getSelectedFile();
String fileName = file.getName();
if (!fileName.toLowerCase().endsWith(".png")) {
file = new File(file.getParent(), fileName + ".png");
}
if (!ImageIO.write(image, "PNG" , file)) {
// TODO: Handle file could not be written case
}
}
The above will make sure the file has the correct file extension, unless the user supplied it himself.
I also see another problem in your code. You invoke savechooser.setFileFilter(..) three times. Each invocation will replace the current filter with the new one. You probably want to use savechooser.addChoosableFileFilter(...) instead (and perhaps setFileFilter(..) for the one you want to use as default). The filter will filter the files shown in the dialog, and thus what files the user clicks on, but does not impact the name the user supplied himself. You can get the current filter from savechooser.getFileFilter(), and use that to determine the format to use.
Here's a more complete solution:
JFileChooser savechooser = new JFileChooser();
FileNameExtensionFilter pngFilter = new FileNameExtensionFilter("PNG File", "png")
savechooser.addChoosableFileFilter(pngFilter);
savechooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG File", "jpg"));
savechooser.addChoosableFileFilter(new FileNameExtensionFilter("GIF File", "gif"));
savechooser.setFileFilter(pngFilter); // Default choose PNG
int returnVal = savechooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = savechooser.getSelectedFile();
FileNameExtensionFilter currentFilter = (FileNameExtensionFilter) savechooser.getFileFilter();
String ext = currentFilter.getExtensions()[0];
if (!currentFilter.accept(file)) {
// File does not not have the correct extension, fix it
String fileName = file.getName();
file = new File(file.getParent(), fileName + "." + ext);
}
String format = "jpg".equals(ext) ? "JPEG" : ext; // May not be strictly necessary, just a reminder that file ext != file format
if (!ImageIO.write(image, format , file)) {
// TODO: Handle file could not be written case
}
}
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*/
This should work:
String originalFilename = originalFile.getFileName();
String fileNameNew = originalFilename.substring(0, originalFilename.length()-".ngc".length())+".fnc";
Path newFile = originalFile.resolveSibling(fileNameNew);
To save the output in a different file with a different extension (.fnc), you can use regex(regular expression) to replace that using the replaceFirst method:
Path originalFile ;
String pathName ;
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();
pathName = originalFile.toAbsolutePath().toString().replaceFirst("\\b.ngc\\b", "");
Path newFile = originalFile.resolveSibling(pathName + ".fnc");
File file = new File(newFile.toUri());
file.createNewFile();
}
I have two seperate methods of opening a file.
The first uses a FileChoser with an additional file type filter.
JFileChooser inFileName = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("PCF & TXT Files", "pcf", "txt");
inFileName.setFileFilter(filter);
Component parent = null;
int returnVal = inFileName.showOpenDialog(parent);`
The second uses a JOptionPane but has a loop to ensure the directory chosen exists
String filePath;
File directory;
do{
filePath = JOptionPane.showInputDialog("please enter directory");
directory = new File(filePath);
if (directory.exists()==false){
JOptionPane.showMessageDialog(null,"error with directory");
}
}while(directory.exists()==false);
I'm looking to get the best of both here. To be able to choose a file, using a file filter and also loop that function should that directory not be valid.
I've tried switching around variable names and the various functions in different places but I cant seem to get the loop (".exists" function) to work.
You just need to modify your JFileChooser code to use a loop.
JFileChooser inFileName = new JFileChooser();
File file;
boolean valid = false;
while (!valid) {
int returnVal = inFileName.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = inFileName.getSelectedFile();
valid = file.isDirectory();
else {
valid = returnVal == JFileChooser.CANCEL_OPTION;
}
}
Its worth mentioning that this kind of thing might be better achieved using;
jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.
I have written a Java program that opens all kind of files with a JFileChooser. Then I want to save it in another directory with the JFileChooser save dialog, but it only saves an empty file. What can I do for saving part?
Thanks.
JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.
E.g.
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(contents);
// etc...
}
Edit:
Assuming that you simply have a source file and destination file and want to copy the contents between the two, I'd recommend using something like FileUtils from Apache's Commons IO to do the heavy lifting.
E.g.
FileUtils.copy(source, dest);
Done!
Just in addition to Kris' answer - I guess, you didn't read the contents of the file yet. Basically you have to do the following to copy a file with java and using JFileChooser:
Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
Select the target file with the FileChooser. This again returns a File object
Use a FileWriter with the target File to store the String or byte array from above to that file.
The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.
Something like..
File file = fc.getSelectedFile();
String textToSave = mainTextPane.getText();
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(file));
writer.write(textToSave);
JOptionPane.showMessageDialog(this, "Message saved. (" + file.getName()+")",
"ImPhil HTML Editer - Page Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{ }