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.
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
In my program, I want to sent some files from client to server using socket programming. I'm using the void setMultiSelectionEnabled(boolean b) method so I can choose more than 1 file, but it gives me an error when i try to get the path of the file. Here's my code:
JFileChooser choose = new JFileChooser();
choose.setAcceptAllFileFilterUsed(false);
choose.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "jpeg"));
choose.setAcceptAllFileFilterUsed(true);
choose.setMultiSelectionEnabled(true);
File[] f = choose.getSelectedFiles();
choose.showOpenDialog(this);
String filePath = f.getAbsolutePath();
String fname = f.getName();
Client_ftp cli = new Client_ftp();
if(cli.kirim(filePath, fname)) {
jLabel1.setText("Success. .");
} else {
jLabel1.setText("failed");
}
f is an array. You'll need to index the array before calling the getAbsolutePath() method for each File in f. Make sure to check for null prior to doing so.
Example: f[0].getAbsolutePath();
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);
How to make the user to select the file from only specified folder
int returnVal = fc.showOpenDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
source = file.getAbsolutePath();
fileName = file.getName();
attachText.setText(fileName);
source = source.replace("\\","\\\\");
}
Here I will get the file from any folder, where I want the file only from G:\Project\Attachments. How Can i do this?
File dir = new File("G:\\Project\\Attachments");
FileSystemView fsv = new SingleRootFileSystemView(dir);
JFileChooser fileChooser = new JFileChooser(fsv);
int returnVal = fc.showOpenDialog(fileChooser);
if (returnVal == JFileChooser.APPROVE_OPTION) {
You can pass the directory in the constructor:
JFileChooser filechooser = new JFileChooser(theDirectory);
or set it
filechooser.setCurrentDirectory(theDirectory);
in your case the directory is:
File theDirectory = new File("G:\\Project\\Attachments");
I am trying to open a javafx FileChooser in the user directory according to an example I found here.
Here is a fragment of the simple code I am using:
FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);
However, I keep obtaining this warning (complete file paths have been truncated):
Invalid URL passed to an open/save panel: '/Users/my_user'. Using 'file://localhost/Users/my_user/<etc>/' instead.
I verified that the file object is an existing directory adding these lines:
System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true
Then I do not have idea why I am obtaining the warning message.
UPDATE:
This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160
(you need to create a free Jira account to see the bug report).
This problem happens in OSX, no idea about other platforms.
This is what I ended up doing and it worked like a charm.
Also, make sure your folder is accessible when trying to read it (good practice). You could create the file and then check if you can read it. Full code would then look like this, defaulting to c: drive if you can't access user directory.
FileChooser fileChooser = new FileChooser();
//Extention filter
FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fileChooser.getExtensionFilters().add(extentionFilter);
//Set to user directory or go to default if cannot access
String userDirectoryString = System.getProperty("user.home");
File userDirectory = new File(userDirectoryString);
if(!userDirectory.canRead()) {
userDirectory = new File("c:/");
}
fileChooser.setInitialDirectory(userDirectory);
//Choose the file
File chosenFile = fileChooser.showOpenDialog(null);
//Make sure a file was selected, if not return default
String path;
if(chosenFile != null) {
path = chosenFile.getPath();
} else {
//default return value
path = null;
}
This works on Windows and Linux, but might be different on other operating systems (not tested)
Try:
String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
#FXML private Label label1; //total file path print
#FXML private Label labelFirst; //file dir path print
private String firstPath; //dir path save
public void method() {
FileChooser fileChooser = new FileChooser();
if (firstPath != null) {
File path = new File(firstPath);
fileChooser.initialDirectoryProperty().set(path);
}
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
new ExtensionFilter("All Files", "*.*") );
File selectFile = fileChooser.showOpenDialog(OwnStage);
if (selectFile != null){
String path = selectFile.getPath();
int len = path.lastIndexOf("/"); //no detec return -1
if (len == -1) {
len = path.lastIndexOf("\\");
}
firstPath = path.substring(0, len);
labelFirst.setText("file path : " + firstPath);
label1.setText("First File Select: " + path);
}
}