Java.Com.ing

Программирование на Java

5497f1e3
7 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java get current directory

Получение текущего рабочего каталога в Java

682 Qazi [2011-02-02 08:24:00]

Я хочу получить доступ к текущему рабочему каталогу, используя

Мой вывод неверен, потому что диск C не является моим текущим каталогом. Нужна помощь в этом отношении.

19 ответов

801 Anuj Patel [2011-09-30 00:12:00]

Здесь будет напечатан полный абсолютный путь , от которого было инициализировано ваше приложение.

270 geoO [2013-04-11 20:10:00]

Используя java.nio.file.Path и java.nio.file.Paths , вы можете сделать следующее, чтобы показать, что Java — это ваш текущий путь. Это для 7 и дальше, и использует NIO.

Это выводит Current relative path is: /Users/george/NetBeansProjects/Tutorials , что в моем случае я запускал класс. Построить пути относительно, не используя ведущий разделитель, чтобы указать, что вы строите абсолютный путь, будет использовать этот относительный путь как отправную точку.

Ниже описаны работы на Java 7 и выше (см. здесь для документации).

Что заставляет вас думать, что c:windowssystem32 не является вашим текущим каталогом? Свойство user.dir явно является «текущим рабочим каталогом пользователя».

Иными словами, если вы не запускаете Java из командной строки, c:windowssystem32, вероятно, является вашим CWD. То есть, если вы дважды щелкните, чтобы запустить свою программу, CWD вряд ли будет каталогом, который вы дважды щелкаете.

Изменить: похоже, что это верно только для старых окон и/или версий Java.

Это решение для меня

19 Bigoloo [2014-01-22 08:20:00]

Это отлично работает и в JAR файлах. Вы можете получить CodeSource ProtectionDomain#getCodeSource() , а ProtectionDomain в свою очередь можно получить с помощью Class#getProtectionDomain() .

обычно, как объект File:

вам может потребоваться полная строка, например «D:/a/b/c»:

11 Bohdan [2013-12-28 06:11:00]

Я нахожусь в Linux и получаю тот же результат для обоих этих подходов:

Использование Windows user.dir возвращает каталог, как ожидалось, но НЕ, когда вы запускаете приложение с повышенными правами (запускаетесь как admin), в этом случае вы получаете C:WINDOWSsystem32

3 JSS [2012-09-27 13:09:00]

Надеюсь, вы хотите получить доступ к текущему каталогу, включая пакет i.e. Если ваша программа Java находится в c:myAppcomfoosrcserviceMyTest.java и вы хотите печатать до c:myAppcomfoosrcservice , тогда вы можете попробовать следующий код:

Примечание. Этот код тестируется только в Windows с Oracle JRE.

3 MJB [2011-02-02 08:37:00]

Текущий рабочий каталог определяется по-разному в разных реализациях Java. Для определенной версии до Java 7 не было последовательного способа получить рабочий каталог. Вы можете обойти это, запустив файл Java с помощью -D и определяя переменную для хранения информации

Это не совсем правильно, но вы поняли эту идею. Тогда System.getProperty(«com.mycompany.workingDir») .

3 Mark [2017-09-15 23:01:00]

Это даст вам путь к вашему рабочему каталогу:

Читать еще:  Разработка web приложений на java

И это даст вам путь к файлу с именем «Foo.txt» в рабочем каталоге:

Упомяните, что он проверяется только в Windows , но я думаю, что он отлично работает на других операционных системах [ Linux,MacOs,Solaris ]:).

У меня были файлы 2 .jar в том же каталоге. Я хотел от одного файла .jar запустить другой файл .jar , который находится в том же каталоге.

Проблема заключается в том, что при запуске из cmd текущий каталог system32 .

  • Ниже показано, что все работает хорошо во всех тестах, которые я сделал даже с именем папки ;][[;’57f2g34g87-8+9-09!2#@!$%^^&() или ()%&$%^@# он работает хорошо.
  • Я использую ProcessBuilder следующим образом:

В Linux, когда вы запустите файл jar из терминала, оба они вернут тот же String : «/home/CurrentUser» , независимо от того, где находится файл jar jar. Это зависит только от того, какой текущий каталог вы используете с вашим терминалом, когда вы запускаете файл jar.

Если ваш Class с main будет называться MainClass , попробуйте:

Это вернет String с абсолютным путем файла jar.

1 bachden [2015-04-16 07:39:00]

Предположим, что вы пытаетесь запустить проект внутри eclipse или netbean или автономно из командной строки. Я написал метод для его исправления.

Чтобы использовать, везде, где вы хотите получить базовый путь для чтения файла, вы можете передать свой класс привязки вышеприведенному методу, результат может быть то, что вам нужно: D

Ни один из ответов, размещенных здесь, не работал у меня. Вот что работало:

Изменить: окончательная версия в моем коде:

Getting the Current Working Directory in Java

I want to access my current working directory using

My output is not correct because C drive is not my current directory. Need help in this regard.

20 Answers 20

This will print a complete absolute path from where your application was initialized.

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:

Читать еще:  Arrays copyof java

* Update * To get current working directory:

This is the solution for me

I’ve found this solution in the comments which is better than others and more portable:

What makes you think that c:windowssystem32 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:windowssystem32 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:WINDOWSsystem32

I hope you want to access the current directory including the package i.e. If your Java program is in c:myAppcomfoosrcserviceMyTest.java and you want to print until c:myAppcomfoosrcservice 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 .

Get the Current Working Directory in Java

Last modified: July 29, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

It’s an easy task to get the current working directory in Java, but unfortunately, there’s no direct API available in the JDK to do this.

In this tutorial, we’ll learn how to get the current working directory in Java with java.lang.System, java.io.File, java.nio.file.FileSystems, and java.nio.file.Paths.

2. System

Let’s begin with the standard solution using System#getProperty, assuming our current working directory name is Baeldung throughout the code:

We used a Java built-in property key user.dir to fetch the current working directory from the System‘s property map. This solution works across all JDK versions.

3. File

Let’s see another solution using java.io.File:

Here, the File#getAbsolutePath internally uses System#getProperty to get the directory name, similar to our first solution. It’s a nonstandard solution to get the current working directory, and it works across all JDK versions.

4. FileSystems

Another valid alternative would be to use the new java.nio.file.FileSystems API:

This solution uses the new Java NIO API, and it works only with JDK 7 or higher.

5. Paths

And finally, let’s see a simpler solution to get the current directory using java.nio.file.Paths API:

Here, Paths#get internally uses FileSystem#getPath to fetch the path. It uses the new Java NIO API, so this solution works only with JDK 7 or higher.

6. Conclusion

In this tutorial, we explored four different ways to get the current working directory in Java. The first two solutions work across all versions of the JDK whereas the last two work only with JDK 7 or higher.

We recommend using the System solution since it’s efficient and straight forward, we can simplify it by wrapping this API call in a static utility method and access it directly.

The source code for this tutorial is available over on GitHub – it is a Maven-based project, so it should be easy to import and run as-is.

Ссылка на основную публикацию