- JFileChooser change default directory in Windows
- 7 Answers 7
- How to create a directory in Java?
- 16 Answers 16
- mkdir vs mkdirs
- How to get the current working directory in Java?
- 24 Answers 24
- Java 11 and newer
- Creating and Reading Directories
- Listing a File System’s Root Directories
- Creating a Directory
- Creating a Temporary Directory
- Listing a Directory’s Contents
- Filtering a Directory Listing By Using Globbing
- Writing Your Own Directory Filter
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?
7 Answers 7
You can use the API method setCurrentDirectory when initializing your JFileChooser objects:
Sample usage might be like:
why don’t you just give the FileChooser the path when you create it, like:
Sorry for taking your time, Just found the answer myself:
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’.
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.
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.
How to create a directory in Java?
How do I create Directory/folder?
Once I have tested System.getProperty(«user.home»);
I have to create a directory (directory name «new folder» ) if and only if new folder does not exist.
16 Answers 16
7 year, I will update it to better approach which is suggested by Bozho.
Here «directory» is the name of the directory you want to create/exist.
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
If you want to create a hierarchy of folder structure use mkdirs
Create a single directory.
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
How to get the current working directory in Java?
I want to access my current working directory using java.
My output is not correct because C drive is not my current directory.
How to get the current directory ?
24 Answers 24
Code :
This will print the absolute path of the current directory from where your application was initialized.
Explanation:
java.io package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir and is the directory from where the JVM was invoked.
Using java.nio.file.Path and java.nio.file.Paths , you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.
This outputs Current relative path is: /Users/george/NetBeansProjects/Tutorials that in my case is where I ran the class from. Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.
The following works on Java 7 and up (see here for documentation).
This will give you the path of your current working directory:
And this will give you the path to a file called «Foo.txt» in the working directory:
Edit : To obtain an absolute path of current directory:
* Update * To get current working directory:
Java 11 and newer
This solution is better than others and more portable:
This is the solution for me
What makes you think that c:\windows\system32 is not your current directory? The user.dir property is explicitly to be «User’s current working directory».
To put it another way, unless you start Java from the command line, c:\windows\system32 probably is your CWD. That is, if you are double-clicking to start your program, the CWD is unlikely to be the directory that you are double clicking from.
Edit: It appears that this is only true for old windows and/or Java versions.
This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain() .
generally, as a File object:
you may want to have full qualified string like «D:/a/b/c» doing:
I’m on Linux and get same result for both of these approaches:
On Linux when you run a jar file from terminal, these both will return the same String : «/home/CurrentUser», no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.
If your Class with main would be called MainClass , then try:
This will return a String with absolute path of the jar file.
Using Windows user.dir returns the directory as expected, but NOT when you start your application with elevated rights (run as admin), in that case you get C:\WINDOWS\system32
I hope you want to access the current directory including the package i.e. If your Java program is in c:\myApp\com\foo\src\service\MyTest.java and you want to print until c:\myApp\com\foo\src\service then you can try the following code:
Note: This code is only tested in Windows with Oracle JRE.
Mention that it is checked only in Windows but i think it works perfect on other Operating Systems [ Linux,MacOs,Solaris ] :).
I had 2 .jar files in the same directory . I wanted from the one .jar file to start the other .jar file which is in the same directory.
The problem is that when you start it from the cmd the current directory is system32 .
- The below seems to work pretty well in all the test i have done even with folder name ;][[;’57f2g34g87-8+9-09!2#@!$%^^&() or ()%&$%^@# it works well.
- I am using the ProcessBuilder with the below as following:
assume that you’re trying to run your project inside eclipse, or netbean or stand alone from command line. I have write a method to fix it
To use, everywhere you want to get base path to read file, you can pass your anchor class to above method, result may be the thing you need 😀
Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with -D and defining a variable to hold the info
That’s not quite right, but you get the idea. Then System.getProperty(«com.mycompany.workingDir») .
This is my silver bullet when ever the moment of confusion bubbles in.(Call it as first thing in main). Maybe for example JVM is slipped to be different version by IDE. This static function searches current process PID and opens VisualVM on that pid. Confusion stops right there because you want it all and you get it.
This isn’t exactly what’s asked, but here’s an important note: When running Java on a Windows machine, the Oracle installer puts a «java.exe» into C:\Windows\system32, and this is what acts as the launcher for the Java application (UNLESS there’s a java.exe earlier in the PATH, and the Java app is run from the command-line). This is why File(«.») keeps returning C:\Windows\system32, and why running examples from macOS or *nix implementations keep coming back with different results from Windows.
Unfortunately, there’s really no universally correct answer to this one, as far as I have found in twenty years of Java coding unless you want to create your own native launcher executable using JNI Invocation, and get the current working directory from the native launcher code when it’s launched. Everything else is going to have at least some nuance that could break under certain situations.
Try something like this I know I am late for the answer but this obvious thing happened in java8 a new version from where this question is asked but..
This will work and show you the current path but I don’t now why java fails to find current dir in new File(«»); besides I am using Java8 compiler.
This works just fine I even tested it new File(new File(«»).getAbsolutePath());
Now you have current directory in a File object so (Example file object is f then),
f.getAbsolutePath() will give you the path in a String varaible type.
Tested in another directory that is not drive C works fine
Creating and Reading Directories
Some of the methods previously discussed, such as delete , work on files, links and directories. But how do you list all the directories at the top of a file system? How do you list the contents of a directory or create a directory?
This section covers the following functionality specific to directories:
Listing a File System’s Root Directories
You can list all the root directories for a file system by using the FileSystem.getRootDirectories method. This method returns an Iterable , which enables you to use the enhanced for statement to iterate over all the root directories.
The following code snippet prints the root directories for the default file system:
Creating a Directory
You can create a new directory by using the createDirectory(Path, FileAttribute ) method. If you don’t specify any FileAttributes , the new directory will have default attributes. For example:
The following code snippet creates a new directory on a POSIX file system that has specific permissions:
To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method, createDirectories(Path, FileAttribute ) . As with the createDirectory(Path, FileAttribute ) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:
The directories are created, as needed, from the top down. In the foo/bar/test example, if the foo directory does not exist, it is created. Next, the bar directory is created, if needed, and, finally, the test directory is created.
It is possible for this method to fail after creating some, but not all, of the parent directories.
Creating a Temporary Directory
You can create a temporary directory using one of createTempDirectory methods:
The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-fle directory.
Listing a Directory’s Contents
You can list all the contents of a directory by using the newDirectoryStream(Path) method. This method returns an object that implements the DirectoryStream interface. The class that implements the DirectoryStream interface also implements Iterable , so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories.
The following code snippet shows how to print the contents of a directory:
The Path objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the /tmp directory, the entries are returned with the form /tmp/a , /tmp/b , and so on.
This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the other newDirectoryStream methods, as described later in this page.
Note that if there is an exception during directory iteration then DirectoryIteratorException is thrown with the IOException as the cause. Iterator methods cannot throw exception exceptions.
Filtering a Directory Listing By Using Globbing
If you want to fetch only files and subdirectories where each name matches a particular pattern, you can do so by using the newDirectoryStream(Path, String) method, which provides a built-in glob filter. If you are not familiar with glob syntax, see What Is a Glob?
For example, the following code snippet lists files relating to Java: .class, .java, and .jar files.:
Writing Your Own Directory Filter
Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing the DirectoryStream.Filter interface. This interface consists of one method, accept , which determines whether a file fulfills the search requirement.
For example, the following code snippet implements a filter that retrieves only directories:
Once the filter has been created, it can be invoked by using the newDirectoryStream(Path, DirectoryStream.Filter ) method. The following code snippet uses the isDirectory filter to print only the directory’s subdirectories to standard output:
This method is used to filter a single directory only. However, if you want to find all the subdirectories in a file tree, you would use the mechanism for Walking the File Tree.