- Как получить текущий рабочий каталог в Java?
- 8 ответов
- How to get the current working directory in Java
- 1. Working Directory
- 2. Working Directory for JAR file?
- Download Source Code
- References
- mkyong
- How to get the current working directory in Java?
- 24 Answers 24
- Java 11 and newer
- System Properties
- Reading System Properties
- Writing System Properties
Как получить текущий рабочий каталог в Java?
Допустим, у меня есть основной класс в C:\Users\Justian\Documents\ . Как я могу заставить свою программу показать, что она находится в C:\Users\Justian\Documents ?
Жесткое кодирование — не вариант, его нужно адаптировать, если оно перемещено в другое место.
Я хочу поместить кучу файлов CSV в папку, заставить программу распознавать все файлы, затем загружать данные и манипулировать ими. Я действительно хочу знать, как перейти к этой папке.
8 ответов
Одним из способов будет использование системное свойство System.getProperty(«user.dir»); это даст вам« Текущий рабочий каталог, когда свойства были инициализированы » , Это, вероятно, то, что вы хотите. чтобы узнать, где была введена команда java , в вашем случае, в каталоге с файлами для обработки, даже если сам файл .jar может проживать где-то еще на машине. Наличие каталога фактического файла .jar в большинстве случаев не очень полезно.
Следующая команда распечатает текущий каталог, из которого была вызвана команда, независимо от того, где находится файл .class или .jar, в котором находится файл .class.
если вы находитесь в /User/me/ и ваш файл .jar, содержащий указанный выше код, находится в /opt/some/nested/dir/ команда java -jar /opt/some/nested/dir/test.jar Test выведет current dir = /User/me .
В качестве бонуса вы также должны рассмотреть возможность использования хорошего объектно-ориентированного парсера аргументов командной строки. Я настоятельно рекомендую JSAP , анализатор простых аргументов Java. Это позволит вам использовать System.getProperty(«user.dir») и, в качестве альтернативы, передать что-то еще, чтобы переопределить поведение. Гораздо более приемлемое решение. Это сделает передачу в каталог для обработки очень простой, и вы сможете использовать user.dir , если ничего не было передано.
Используйте CodeSource#getLocation() . Это прекрасно работает и в JAR-файлах. Вы можете получить CodeSource с помощью ProtectionDomain#getCodeSource() и ProtectionDomain в свою очередь можно получить с помощью Class#getProtectionDomain() .
Обновить в соответствии с комментарием ФП:
Я хочу поместить кучу файлов CSV в папку, заставить программу распознавать все файлы, затем загружать данные и манипулировать ими. Я действительно хочу знать, как перейти к этой папке.
Это потребует жесткого кодирования /знания их относительного пути в вашей программе. Скорее рассмотрите добавление его пути к пути к классу, чтобы вы могли использовать ClassLoader#getResource()
Или передать его путь в качестве аргумента main() .
How to get the current working directory in Java
In Java, we can use System.getProperty(«user.dir») to get the current working directory, the directory from where your program was launched.
One of the good things about this system property user.dir is we can easily override the system property via a -D argument, for example:
1. Working Directory
The below program shows different ways like File , Paths , FileSystems , or system property to get the current working directory; all methods will return the same result.
Normally, we use the System.getProperty(«user.dir») to get the current working directory.
2. Working Directory for JAR file?
Do not use System.getProperty(«user.dir») , File or Path to access a file that is inside a JAR file, it is not going to work. Instead, we should use getClassLoader().getResourceAsStream() .
Note
The above code is extracted from this Read a file from resources folder. Refer to example 2 for accessing a file that is inside a JAR file.
Download Source Code
References
mkyong
When working with Spring MVC on tomcat, for some reason i get a path to tomcat’s “bin” folder from this property
We can override the system property user.dir , pass a -Duser.dir=/home/mkyong/ to the VM arguments.
Hi mkyong, I found some problem on Linux system, could you help me?
System: Ubuntu 13.10
IDE : Netbeans 7.4
Java version: 1.7.0_45
My application have a configuration file which plan to place on same directory of .jar. But when i generate my project to .jar and run it. Default working directory set to my home folder “/home/[username]/” instead of the location of .jar. So i can’t get the configuration file.
I try “MYCLASS.class.getProtectionDomain().getCodeSource().getLocation().getPath()”, but this is refer to “[PROJECTDIRECTORY]/build/classes” when i debugging on IDE.
is there any good idea to place a file something like configuration file?
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
System Properties
In Properties, we examined the way an application can use Properties objects to maintain its configuration. The Java platform itself uses a Properties object to maintain its own configuration. The System class maintains a Properties object that describes the configuration of the current working environment. System properties include information about the current user, the current version of the Java runtime, and the character used to separate components of a file path name.
The following table describes some of the most important system properties
Key | Meaning |
---|---|
«file.separator» | Character that separates components of a file path. This is » / » on UNIX and » \ » on Windows. |
«java.class.path» | Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property. |
«java.home» | Installation directory for Java Runtime Environment (JRE) |
«java.vendor» | JRE vendor name |
«java.vendor.url» | JRE vendor URL |
«java.version» | JRE version number |
«line.separator» | Sequence used by operating system to separate lines in text files |
«os.arch» | Operating system architecture |
«os.name» | Operating system name |
«os.version» | Operating system version |
«path.separator» | Path separator character used in java.class.path |
«user.dir» | User working directory |
«user.home» | User home directory |
«user.name» | User account name |
Reading System Properties
The System class has two methods used to read system properties: getProperty and getProperties .
The System class has two different versions of getProperty . Both retrieve the value of the property named in the argument list. The simpler of the two getProperty methods takes a single argument, a property key For example, to get the value of path.separator , use the following statement:
The getProperty method returns a string containing the value of the property. If the property does not exist, this version of getProperty returns null.
The other version of getProperty requires two String arguments: the first argument is the key to look up and the second argument is a default value to return if the key cannot be found or if it has no value. For example, the following invocation of getProperty looks up the System property called subliminal.message . This is not a valid system property, so instead of returning null, this method returns the default value provided as a second argument: » Buy StayPuft Marshmallows! «
The last method provided by the System class to access property values is the getProperties method, which returns a Properties object. This object contains a complete set of system property definitions.
Writing System Properties
To modify the existing set of system properties, use System.setProperties . This method takes a Properties object that has been initialized to contain the properties to be set. This method replaces the entire set of system properties with the new set represented by the Properties object.
The next example, PropertiesTest , creates a Properties object and initializes it from myProperties.txt .
PropertiesTest then uses System.setProperties to install the new Properties objects as the current set of system properties.
Note how PropertiesTest creates the Properties object, p , which is used as the argument to setProperties :
This statement initializes the new properties object, p , with the current set of system properties, which in the case of this small application, is the set of properties initialized by the runtime system. Then the application loads additional properties into p from the file myProperties.txt and sets the system properties to p . This has the effect of adding the properties listed in myProperties.txt to the set of properties created by the runtime system at startup. Note that an application can create p without any default Properties object, like this:
Also note that the value of system properties can be overwritten! For example, if myProperties.txt contains the following line, the java.vendor system property will be overwritten:
In general, be careful not to overwrite system properties.
The setProperties method changes the set of system properties for the current running application. These changes are not persistent. That is, changing the system properties within an application will not affect future invocations of the Java interpreter for this or any other application. The runtime system re-initializes the system properties each time its starts up. If changes to system properties are to be persistent, then the application must write the values to some file before exiting and read them in again upon startup.