opening a javafx FileChooser in the user directory - java

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

Related

Validate Excel file is downloaded in Selenium Web driver Java

I'm able to download excel file by clicking Download button which comes under DOM ,
after that i want verify downloaded file is same one.
AUTO IT is not allowed in project.
I have tried below code for verification on local but if i will push this code to repo.
then user path will get change and code will fail.
`String filepath = "C:User\\Dhananjay\\Downloads";
String fileName = "report.xlsx"
File targetFile = new File(fileName,filePath);
if(! targetFile.exists())'
{
system.out.println("File is verified")`
}else{
system.out.println("file not downloaded")
}'
String userProfile = System.getProperty("user.home"); returns %USERPROFILE% variable.
So you can use String filepath = System.getProperty("user.home") + "\\Downloads";
Works even on Linux.
I have found way to validate on local path and it's generic one
File folder = new File(System.getProperty("user.home") +\\Downloads);
File[] listOfFiles = folder.listFiles();
boolean found = false;
File f = null;
for (File listOfFile : listOfFiles) {
if (listOfFile.isFile()) {
String fileName = listOfFile.getName();
System.out.println("File " + listOfFile.getName());
if (fileName.matches("5MB.zip")) {
f = new File(fileName);
found = true;
}
}
}
Assert.assertTrue("Downloaded document is not found",found );
f.deleteOnExit();

Add extension with jFileChooser

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

Using image from same folder as compiled Jar not working

All I am trying to do is create a JLabel using an image located in the same directory as the .jar and if it does not exist it will load a default photo located inside the .jar iteself. The picture exists in the folder however it always defaults to the picture inside the .jar
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File logo = new File(path + "logo.png");
JLabel lblNewLabel_1;
if (logo.exists()){
lblNewLabel_1 = new JLabel(new ImageIcon(logo.getPath()));
} else {
lblNewLabel_1 = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/Coffee.png")));
}
frame.getContentPane().add(lblNewLabel_1, BorderLayout.WEST);
final JLabel lblStatus = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/status1.png")));
frame.getContentPane().add(lblStatus, BorderLayout.EAST);
The most simple way to diagnose this issue is to apply simple System.out.println() like here
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath(;
System.our.println("Jar path is "+path); <- you will see the actual path content here
File logo = new File(path + "logo.png");
Check the result and adjust concatenate path as needed. I guess that path is either pointing to different directory than you think it is, or it is simply missing a File.separator at the end. Try out and share the results!
It looks like you are missing a '/' at the end of path. Do it this way:
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File logo = new File(new File(path).getParentFile(), "logo.png");
...
The catch is to first creating a File for the containing directory and then using the constructor File(File dir, String name) instead of string concatenation.
Furthermore, you should check folder and file permissions in advance, providing proper logging output for error diagnosis. For this, use canRead() instead of exists() (assuming log is available as some logging facility - replace with the logging mechanism of your choice):
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File sourceLocation = new File(path);
// go up in the hierarchy until there is a directory
while (sourceLocation != null && !sourceLocation.isDirectory()) {
sourceLocation = sourceLocation.getParentFile();
if (sourceLocation == null) {
log.warn(path + " is not a directory but has no parent");
}
}
if (sourceLocation != null && sourceLocation.canRead()) {
File logo = new File(sourceLocation, "logo.png");
if (logo.canRead()) {
log.info("Using logo " + logo.getAbsolutePath());
lblNewLabel_1 = new JLabel(new ImageIcon(logo.getPath()));
} else {
log.warn("can not read " + logo.getAbsolutePath());
}
}
if (lblNewLabel_1 == null) {
log.warn("logo location not accessible, using default logo: " + sourceLocation);
lblNewLabel_1 = new JLabel(new ImageIcon(Main.class.getResource("/com/daniel/Coffee.png")));
}
// ...

JFileChooser getCurrentDirectory() to String

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.

JFileChooser select directory but show files

I feel like there should be a simple way to do this but I can't figure it out. I have a JFileChooser that allows the user to select directories. I want to show all the files in the directories to give the user some context, but only directories should be accepted as selections (maybe the Open button would be disabled when a file is selected). Is there an easy way of doing this?
My solution is a merge between the answers of camickr and trashgod:
final JFileChooser chooser = new JFileChooser() {
public void approveSelection() {
if (getSelectedFile().isFile()) {
return;
} else
super.approveSelection();
}
};
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
See setFileSelectionMode() in How to Use File Choosers:
setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
Addendum: The effect can be see by uncommenting line 73 of this FileChooserDemo, but it appears to be platform-dependent.
Addendum: If using FILES_AND_DIRECTORIES, consider changing the button text accordingly:
chooser.setApproveButtonText("Choose directory");
As the effect is L&F dependent, consider using DIRECTORIES_ONLY on platforms that already meet your UI requirements:
if (System.getProperty("os.name").startsWith("Mac OS X")) {
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
Override the approveSelection() method. Something like:
JFileChooser chooser = new JFileChooser( new File(".") )
{
public void approveSelection()
{
if (getSelectedFile().isFile())
{
// beep
return;
}
else
super.approveSelection();
}
};
The solution of overriding approveSelection can be annoying for certain users.
Sometimes, a user would just click on a file in a directory for no reason (even though she wants to select the directory and not the file). If that happens, the user would be (kind-a) stuck in the JFileChooser as the approveSelection will fail, even if she deselects the file. To avoid this annoyance, this is what I do:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_AND_DIRECTORIES);
int option = fileChooser.showDialog(null,
"Select Directory");
if (option == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
// if the user accidently click a file, then select the parent directory.
if (!f.isDirectory()) {
f = f.getParentFile();
}
System.out.println("Selected directory for import " + f);
}
Selecting the directory, even when the user selected a file results in a better usability in my opinion.
AFAIK JFileChooser separates file filtering (what can be viewed, very configurable) from selection filtering (what can be chosen).
The configuration of selection filtering is much more limited, but AFAIK you can choose to allow only dirs or only files to be selected with setFileSelectionMode()
Keep the fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) and use:
File[] selectedFiles = fileChooser.getSelectedFile().listFiles();
The JFileChooser supports three selection modes: files only, directories only, and files and directories. In your case what you need is :
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
source : http://www.java2s.com/Tutorial/Java/0240__Swing/TheJFileChoosersupportsthreeselectionmodesfilesonlydirectoriesonlyandfilesanddirectories.htm
Select Multiple Folders But Show All Included files
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class MultipleFilesAndDirectoryChooserButDisplayFiles {
public static void main(String[] args) {
ArrayList<File> tempFiles = new ArrayList<>();
ArrayList<File> finalFiles = new ArrayList<>();
ArrayList<String> relativeFiles = new ArrayList<>();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose File To Transfer");
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setMultiSelectionEnabled(true);
int returnVal = fileChooser.showOpenDialog(null);
fileChooser.approveSelection();
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileChooser.approveSelection();
var fileAddress = fileChooser.getSelectedFiles();
for (var arrElement : fileAddress) {
tempFiles.add(arrElement);
File baseFile;
baseFile = arrElement.getParentFile();
Iterator<File> iterator = tempFiles.iterator();
while (iterator.hasNext()) {
File file = iterator.next();
if (file.isDirectory()) {
var enclosedFiles = file.listFiles();
if (enclosedFiles != null) {
if (enclosedFiles.length != 0) {
var index = tempFiles.indexOf(file);
tempFiles.remove(file);
tempFiles.addAll(index, Arrays.asList(enclosedFiles));
iterator = tempFiles.iterator();
} else {
tempFiles.remove(file);
finalFiles.add(file);
relativeFiles.add(baseFile.toURI().relativize(file.toURI()).getPath());
iterator = tempFiles.iterator();
}
}
} else if (file.isFile()) {
tempFiles.remove(file);
finalFiles.add(file);
relativeFiles.add(baseFile.toURI().relativize(file.toURI()).getPath());
iterator = tempFiles.iterator();
}
}
}
for (var relativeFile : relativeFiles) {
System.out.println(relativeFile);
}
for (var file : finalFiles) {
System.out.println(file);
}
}
}
}
Output:
Folder1/EmptyFolder/
Folder1/SubFolder1/1.1.txt
Folder1/SubFolder1/1.2.txt
Folder1/SubFolder1/1.3.txt
Folder1/SubFolder1/SubFolder 1.1/1.1.1.txt
Folder1/SubFolder1/SubFolder 1.1/1.2.1.txt
Folder1/SubFolder1/SubFolder 1.1/1.3.1.txt
Folder1/SubFolder2/2.1/2.1.1.txt
Folder1/SubFolder2/2.1/2.1.2.txt
Folder1/SubFolder2/2.1/2.1.3.txt
Folder1/SubFolder3/3.1.txt
Folder1/SubFolder3/3.2.txt
Folder1/SubFolder3/3.3.txt
Folder2/Sub Folder/2.1.txt
Folder2/Sub Folder/EmptyFolder/
file1.txt
file2.txt
E:\Folder1\EmptyFolder
E:\Folder1\SubFolder1\1.1.txt
E:\Folder1\SubFolder1\1.2.txt
E:\Folder1\SubFolder1\1.3.txt
E:\Folder1\SubFolder1\SubFolder 1.1\1.1.1.txt
E:\Folder1\SubFolder1\SubFolder 1.1\1.2.1.txt
E:\Folder1\SubFolder1\SubFolder 1.1\1.3.1.txt
E:\Folder1\SubFolder2\2.1\2.1.1.txt
E:\Folder1\SubFolder2\2.1\2.1.2.txt
E:\Folder1\SubFolder2\2.1\2.1.3.txt
E:\Folder1\SubFolder3\3.1.txt
E:\Folder1\SubFolder3\3.2.txt
E:\Folder1\SubFolder3\3.3.txt
E:\Folder2\Sub Folder\2.1.txt
E:\Folder2\Sub Folder\EmptyFolder
E:\file1.txt
E:\file2.txt
I think the best solution is just to allow the user to select either a file or a directory. And if the user select a file just use the directory where that file is located.

Categories

Resources