I am writing a program that opens a file and loads all the file contents into a JTextArea. I want to restrict users from being able to open different file formats. The formats i want to accept include: .js .php .html .asmx .htm .css basically any format readable in a web browser.
What is the best way to do this?
Should I use a regular expression to check if the file's name matches my criteria or is there a simpler solution?
Here is kind of what I had in mind:
String fileExtensions = "(.js|.php|.html|.asmx|.htm|.css)$"; // $ end of line regex
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
String fileName = file.toString();
Pattern pattern = Pattern.compile(fileExtensions);
Matcher matcher = pattern.matcher(fileName);
if (matcher.find()) {
openAndReadFile(); // opens the file and outputs contents
} else {
// prompt the user to open a different file
}
} else {
// do nothing because cancel was pressed
}
Any suggestions?
Do you have to use regex? The most appropriate way to do this would be a FileNameExtensionFilter
Example (from the FileNameExtensionFilter API):
FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
JFileChooser fileChooser = ...;
fileChooser.addChoosableFileFilter(filter);
Related
I'm creating a program which will create files with different extensions. For that, i'm using the JFileChooser. I've set the FileFilter to accept only my desired extensions, but when I select one, I still have to add the extension in the name of the file myself. How can I solve that? Many thanks!
You basically have to add the extension yourself after the user closes the dialog.
This example allows the user to specify a file ending with ".foo" or ".bar" and will add that extension if the user did not do so.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .foo", "foo"));
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .bar", "bar"));
int option = fileChooser.showSaveDialog(null);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file!=null) {
FileFilter fileFilter = fileChooser.getFileFilter();
if (fileFilter instanceof FileNameExtensionFilter && ! fileFilter.accept(file)) {
// if the filter doesn't accept the filename, that must be because it doesn't have the correct extension
// so change the extension to the first extension offered by the filter.
FileNameExtensionFilter fileNameExtensionFilter = (FileNameExtensionFilter) fileFilter;
String extension = fileNameExtensionFilter.getExtensions()[0];
String newName = file.getName() + "." + extension;
file = new File(file.getParent(), newName);
}
System.out.println("The selected file is: " + file.getAbsolutePath());
}
}
For that you have to get the filefilter selected by the user after he presses the validating button of the JFileChooser and compare the filefilter description with the list of your extensions before initializing the file object with the specified extension in your code if there is a match. I don't know if you will understand me.
Modelexcel model = new Modelexcel();
JFileChooser selectFile = new JFileChooser();;
File file;
JButton btnExporterVersExcel = new JButton("Exporter vers Excel");
btnExporterVersExcel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(selectFile.showDialog(null, "Exporter")==JFileChooser.APPROVE_OPTION) {
String extension=selectFile.getFileFilter().getDescription();
if(extension.contains("(*.xlsx)")) {
file= new File(selectFile.getSelectedFile()+".xlsx");
}else if(extension.contains("(*.xls)")){
file= new File(selectFile.getSelectedFile()+".xls");
}
if(file.getName().endsWith("xls") ||
file.getName().endsWith("xlsx")) {
JOptionPane.showMessageDialog(null, model.Export(file, table));
}else {
JOptionPane.showMessageDialog(null, "Format invalid");
}
}
}
});
This is a fragment of my code to save files in ".xls" and ".xlsx" formats. Hope a look through it will help you
I have no problem opening multiple file types, however I want the option to be able to save multiple file types. I can't figure out how to get the option the user selected to save their file types as.
Here is my code:
//.txt and .encm files are allowed
final JFileChooser txtOrEncmChooser = new JFileChooser(new File(System.getProperty("user.dir")));
//only allow user to use .txt and .encm files
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Encrypted Data File (*.encm)", "encm"));
txtOrEncmChooser.addChoosableFileFilter(new FileNameExtensionFilter("Text File (*.txt)", "txt"));
txtOrEncmChooser.setAcceptAllFileFilterUsed(false);
//displays save file dialog
int returnVal = txtOrEncmChooser.showSaveDialog(FileEncryptionFilter.this);
//use chose to save file
if (returnVal == JFileChooser.APPROVE_OPTION)
{
//selects file
File fileName = txtOrEncmChooser.getSelectedFile();
/****The problem is here, how do I figure out what file type the user selected?****/
if .txt is selected{
String filePath = fileName.getPath() + ".txt"; //file path
}
else if .encm is selected
{
String filePath = fileName.getPath() + ".encm"; //file path
}
}
I have searched the forums for solutions, but I only found the solution for opening multiple file types, not saving multiple file types.
https://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html#getFileFilter()
FileNameExtensionFilter f = (FileNameExtensionFilter) txtOrEncmChooser.getFileFilter();
Since getExtensions() returns an array, you'll have to iterate through all the extensions. If you are sure that it only contains one element, of course, you won't need to do this. Just check f.getExtensions()[0].equals("txt"), for example. You could also create your file filters as local variables and then compare them with the selected one.
I have a simple JFileChooser set up in the following manner
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new FileFilter() {
...
});
int v = chooser.showOpenDialog(this);
if (v == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
System.out.println(file.getAbsolutePath());
}
As you can see, this FileChooser starts out in the current directory, which in my Netbeans project, is the root of the project folder. Here's the problem: When I select a file and it prints out the absolute path, it includes the "." in the path. For instance, the output I get is:
/Users/MyName/Folder1/Folder2/./Temp.xls
Of course, this is weird, especially since I'm displaying this to the user. Now, I could be hacky and do some fun post substring processing stuff to get rid of that "/./" portion. But...is there a non-lazy programmer way to fix this problem? Thanks in advance!
Use the system property "user.dir" as follows:
File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);
I have this code:
JFileChooser openFolder = new JFileChooser();
openFolder.setCurrentDirectory(new java.io.File("."));
openFolder.setDialogTitle("Select target directory");
openFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
openFolder.setAcceptAllFileFilterUsed(false);
if (openFolder.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File newLoc = openFolder.getCurrentDirectory();
}
How can I make it so that It converts this:
File newLoc = openFolder.getCurrentDirectory();
To a String if its possible?
For example using the FileChooser I chose the folder: C:\Music
I tried using:
String locToString = FileUtils.readFileToString(newLoc);
but it doesn't work.
I want to convert it to string so I can make it appear on a JTextField using:
jTextField.setText(locToString);
newLoc.getAbsolutePath() will give you a String from a File, per the javadoc.
I am exploring Jfilechooser.I already get the file path in the Jfilechooser.Now I want to display the information like file name, file size, location, and access rights.Is their anyway to display those information using the file path only.Anyone can help me?I want it to display in a TextArea.
this is the how I pop up a Jfilechooser.
private void browsebuttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
fieldlocation.setText(filename);
}
Take a look at the JavaDoc for File:
File.getName()
Will return the name of the file
File.length()
Will return the size of the file in bytes
File.getAbsolutePath()
Will return the absolute path of the file
File.canRead()
File.canWrite()
File.canExecute()
Will return your access rights on the file.
One thing I would note about your code is that you don't check the return value from the file chooser. If the user clicks cancel you probably want to abort processing. The way to do this is to check the return value of JFileChoose.showOpenDialog(null); like so:
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Straight from the JavaDoc.
In short I would suggest that you (re)?read the documentation for the APIs you are using. It will save you much time in the long run if you understand your own code.