jfilechooser - set directory to a path in a file - java

I am trying to set the directory path in JFilechooser through something like this(using commons-io ) :
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File theDirectory = new File(fileContents);
filechooser = new JFileChooser();
fileChooser.setCurrentDirectory(theDirectory);
filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
I'm using getCanonicalPath() to get the path and write in the file path.txt
path = file.getCanonicalPath();
I don't intend to put all my code here,but I'm sure that the program writes and reads the path in path.txt.
I don't get any error,but everytime I run the program it always open JFilechooser in my documents folder.What i am doing wrong?

Try to pass the current directory directly in the constructor:
filechooser = new JFileChooser(theDirectory);

If you consult the API, using the default constructor (i.e. new JFileChooser()):
Constructs a JFileChooser pointing to
the user's default directory. This
default depends on the operating
system. It is typically the "My
Documents" folder on Windows, and the
user's home directory on Unix.
This would seem to account for always opening to My Documents, but this isn't your problem. In fact, your problem lies with setting the current directory (i.e. setCurrentDirectory(theDirectory)):
Sets the current directory. Passing in
null sets the file chooser to point to
the user's default directory. This
default depends on the operating
system. It is typically the "My
Documents" folder on Windows, and the
user's home directory on Unix. If the
file passed in as currentDirectory is
not a directory, the parent of the
file will be used as the
currentDirectory. If the parent is not
traversable, then it will walk up the
parent tree until it finds a
traversable directory, or hits the
root of the file system.
That being said, I'd pay attention to the highlighted text since it appears that you're setting a file as the current directory and not a directory.

In your main class declare
public static String dirpath=".";
private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser jfc = new JFileChooser(dirpath);
dirpath =jfc.getSelectedFile().getAbsolutePath().toString();
}

For select the last directory that you open :
chooser.setCurrentDirectory(lastDirectory);
int r = chooser.showOpenDialog(new JPanel());
if (r == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getPath();
lastDirectory = chooser.getSelectedFile();
}

JFileChooser Chooser = new JFileChooser("F:");

if you want to change the directory theb use System.getProperty method
String s=System.getProperty("user.dir"); // changes directory from documents to the user current Directory;
JFileChooser jfc=new JFileChooser(s);

Related

JFileChooser > "Look in" weird names

I have a java application that uses JFileChooser on Win7. The weird thing is that sometimes (quite often) but not always - drive names look weird in 'Look in:' combo box:
Does anyone have an idea what causes that and how to make it always show proper names?
Those come from system drives like My Computer, Network Neighborhood, etc.
The way I get around it showing the files like that is:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileView(new FileView() {
#Override
public String getName(File f) {
String name = FileSystemView.getFileSystemView().getSystemDisplayName(f);
// If names is empty use the description
if(name.equals("")) {
name = FileSystemView.getFileSystemView().getSystemTypeDescription(f);
}
return name;
}
});
This way it is always pulling the names being displayed by the file system.
I want to share a little piece of code which explain the not so obvious behavior of JFileChooser.
On Windows there is a difference if you navigate on the filesystem in a CMD session or in the Windows file explorer.
For example you navigate to the root directory of drive c:\.
CMD
rem this will still stay in C:\ as there is no parent directory
cd ..
Windows file explorer
- the parent directory of 'C:\' is 'Computer'
- but 'Computer' is not a real directory and is accessed by an CLSID (Class Identifier
for COM class objects), the incomprehensible '::{20D04FE0-3AEA-1069-A2D8-08002B30309D}'
The code to make this behaviour more clear.
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class JFileChooserParentDirectory {
public static void main(String[] args) {
// the root directory of drive C:
File file = new File("C:/");
// get a view of the file system
FileSystemView fileSystemView = FileSystemView.getFileSystemView();
// get the parent directory of our file
File parentDir = fileSystemView.getParentDirectory(file);
// get the Windows display name of this parent directory
String displayName = fileSystemView.getSystemDisplayName(parentDir);
// get the Windows type description of this parent directory
String typeDescription = fileSystemView.getSystemTypeDescription(parentDir);
// print out all the different values
String printFormat = "%-50s: %s%n";
System.out.printf(printFormat, "file.getAbsolutePath()", file.getAbsolutePath());
System.out.printf(printFormat, "parentDir.getName()", parentDir.getName());
// this absolute path is related to the directory from which you started the code
System.out.printf(printFormat, "parentDir.getAbsolutePath()", parentDir.getAbsolutePath());
System.out.printf(printFormat, "fileSystemView.getSystemDisplayName(parentDir)", displayName);
System.out.printf(printFormat, "fileSystemView.getSystemTypeDescription(parentDir)", typeDescription);
}
}
This print out.
file.getAbsolutePath() : C:\
parentDir.getName() : ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
parentDir.getAbsolutePath() : D:\development\stackoverflow\playground\::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
fileSystemView.getSystemDisplayName(parentDir) : Computer
fileSystemView.getSystemTypeDescription(parentDir): System Folder
To solve the problem in the JFileChooser take the solution from #inquisitor.

path defined in linux style a final variable. Can't open the path on windows

I don't know what to search for.
I have a external jar library in which there is a class that has all the configurations variables like where to store the log files and such, as public static final variables.
the path for log file config given is "/home/log.cfg".
Now I am working in windows. How do I make a path like this? where to put the cfg file?
The file can still be opened an read if you create the directory home in the root of your drive. Just make sure that the working directory of the application is on the same drive. Java file handling API seems to add the dirve letter to an absolute path if none was specifyed.
javadoc for File#getAbsolutePath
On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
A simple test demonstrates that:
Create a directory under C:\ named home and place some text file inside.
#Test
public void openFile() throws FileNotFoundException, IOException {
File file = new File("/home/log.cfg");
System.out.println(file.getAbsolutePath());
FileInputStream fileInputStream = new FileInputStream("/home/log.cfg");
int c;
while(-1 != (c = fileInputStream.read())) {
System.out.print((char) c);
}
fileInputStream.close();
}
And here is the output:
C:\home\log.cfg
Hello, log.fg!

JFileChooser change default directory in Windows

I want to change the default directory of my JFileChooser to "My Music" on Windows.
This directory is C:\Users\Fre\Music on my account because my username is Fre
The default is set on C:\Users\Fre\Documents (depends on OS i think).
How can I change this?
You can use the API method setCurrentDirectory when initializing your JFileChooser objects:
public void setCurrentDirectory(File dir)
Sample usage might be like:
yourFileChooser.setCurrentDirectory(new File
(System.getProperty("user.home") + System.getProperty("file.separator")+ "Music"));
why don't you just give the FileChooser the path when you create it, like:
JFileChooser chooser = new JFileChooser("C:\\Users\\Fre\\Music\\");
Sorry for taking your time,
Just found the answer myself:
String userhome = System.getProperty("user.home");
JFileChooser fc = new JFileChooser(userhome +"\\Music");
JFileChooser openFile = new JFileChooser("C:\\Users\\Fre\\Music");
Creating all your own code, so as to set a default file directory is unnecessary and lengthy. A much easier and quicker way of doing it is by just right clicking on the File Chooser itself on Design view and right clicking 'customise code'.
Customise Code for File Chooser
This will show you the vital code for that GUI component. From the drop down box next to the top line of code, select 'custom creation'.
This will allow you to customise what fileChooser = is assigned to. Between the curly brackets JFileChooser() you can either hard code in the file directory with speech marks like this.
JFileChooser("C:\Users\user\Documents")
or type in a name that for a variable you created earlier. This variable would hold the file directory. I would recommend the latter option, though either will work fine.
Hope this helps.
p.s. sorry about having to use a link for the photo. I don't have enough privilege yet.
You can Change the default directory of my JFileChooser to "Directory you want" on Windows
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("put here your directory"));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
jTextField.setText(selectedFile.getAbsolutePath());
}
Pretty Simple:
JFileChooser browseImageFile = new JFileChooser("User Defined Directory");

How to get proper path in Java using JFileChooser as per the Operating system

In my Java application I need to select a path using JFileChooser. The code that I have written is as follows:
jfChooser = new JFileChooser();
jfChooser.setCurrentDirectory(new java.io.File("."));
jfChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "+ jfChooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "+ jfChooser.getSelectedFile());
tfPath.setText(jfChooser.getSelectedFile().getAbsolutePath()); // the selected path set to textfield which is lated get by the program
}
else {
System.out.println("No Selection ");
}
I am getting the path properly.For example, here I am getting the path (In Windows os)
String choosedPath=tfPath.getText().trimm();
Now actually I want to create a another directory on a given path (i.e. inside newfolder directory) programatically.
For that I have new directory name "newdir" so the string passed to File constructor for creating this directory is as follows:
File createFolder = new File("choosedPath"+"\\"+"newdir");
Now the problem is that my application may run on windows or may run on Linux so according to that the filepath seperator varies (i.e. '/' for windows and '\' for linux)
How do I Overcome this problem so that I will get propper slashes in path according to OS?
new File(choosedPath, "newDir");
Platform dependent file separator gonna be choose automatically.
You can too use File.separator to get platform dependent separator to construct the string but you going to end with more code than first solution.
Use File.separator instead of / or \.

Find Path During Runtime To Delete File

The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.
The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.

Categories