Using JFileChooser without opening the actual file - java

I'm using the JFileChooser to allow a user to choose a .txt file that will later be processed by my program, however when the user chooses the file, it is actually opened by my computers default app (in my case TeXworks) as well as used by my program. Any idea how I can stop this?
File fileToOpen = fileChooser.getSelectedFile();

JFileChooser's getSelectedFile() method, returns a File object.
Use the getAbsolutePath() to get the absolute name to the file.
Modified example from the JavaDoc:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this directory: " + chooser.getSelectedFile().getAbsolutePath());
}
So in your case you just need to append .getAbsolutePath() to the end of your statement, like this:
File fileToOpen = fileChooser.getSelectedFile().getAbsolutePath();

Related

Is there a way to save my bufferedImage with the extention selected in my JfileChooser?

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
}
}

jfilechooser skips last directory [duplicate]

How can I get the absolute path of a directory using JFileChooser, just selecting the directory?
Use:
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//or
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
together with:
chooser.getCurrentDirectory()
//or
chooser.getSelectedFile();
then call getAbsoluteFile() on the File object returned.
JFileChooser's getSelectedFile() method, returns a File object.
Use the getAbsolutePath() to get the absolute name to the file.
modified example from the javadoc:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this directory: " +
chooser.getSelectedFile().getAbsolutePath());
}
Try:
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File file = chooser.getSelectedFile();
String fullPath = file.getAbsolutePath();
System.out.println(fullPath);
fullPath gives you the required Absolute path of the Selected directory

How to set the last path as the next default using JFileChooser

I have several dialog boxes which provide a File Chooser. For the first, my coding was like this
JFileChooser chooser= new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal= chooser.showOpenDialog(this);
if(returnVal==JFileChooser.APPROVE_OPTION){
File f= chooser.getSelectedFile();
jTextField1.setText(f.getPath());
chooser.setCurrentDirectory(f);
}
In my case, i would like to set the last path which is selected as the default path in next selection JFileChooser. Is there any solution for me?
Thanks for any response
Depending on your requirements, you can use Preferences to store it away and use it again after the program has been restarted.
Preferences pref = Preferences.userRoot();
// Retrieve the selected path or use
// an empty string if no path has
// previously been selected
String path = pref.get("DEFAULT_PATH", "");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Set the path that was saved in preferences
chooser.setCurrentDirectory(new File(path));
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
chooser.setCurrentDirectory(f);
// Save the selected path
pref.put("DEFAULT_PATH", f.getAbsolutePath());
}
You will have to "remember" the last path.
This can easily be done by storing the value in a instance variable...
private File lastPath;
//...
lastPath = f.getParentFile();
And simply resetting it when you need to...
//...
if (lastPath != null) {
chooser.setCurrentDirectory(lastPath);
}
You could also use a single instance of the JFileChooser, so each time you show it, it will be at the last location it was used...

Best way of opening a file (and ensuring file is chosen)

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);

Set default saving extension with JFileChooser

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.");

Categories