Как найти путь к файлу java

% Path

Интерфейс: java.nio.file.Path

Описание

Представляет собой абстракцию пути к элементу файловой системы (файлу, каталогу или чему-то ещё). Понятие “файловой
системы” здесь можно трактовать достаточно широко, и это не обязательно именно дисковая файловая система. Например,
в стандартной библиотеке есть реализация, представляющая ZIP-архив как файловую систему.

Класс Path предназначен только для манипуляции путями как синтаксическими конструкциями, и вовсе не обязательно, что
файл (или другой элемент ФС), на который указывает путь, действительно существует. Объект Path проще всего
рассматривать как ссылку на элемент ФС, которая сама по себе не умеет работать с тем, на что ссылается. Для операций с
самой ФС используется класс Files, принимающий параметры типа Path.

Здесь мы рассмотрим только операции со стандартной ФС.

Создание путей

Чтобы создать объект типа Path с нуля, используется статический метод get в классе Paths:

static Path get(String first, String... more)

Этот метод принимает один и более компонентов пути, разбивает их на отдельные подкомпоненты по платформозависимым
разделителям (/ для Unix, для Windows), и из полученных компонентов создаёт объект типа Path.

Например, на платформе Windows все приведённые примеры эквивалентны:

Path p1 = Paths.get("C:/windows/explorer.exe");
Path p2 = Paths.get("C:\windows\explorer.exe");
Path p3 = Paths.get("C:\windows", "explorer.exe");
Path p4 = Paths.get("C:", "windows", "explorer.exe");

Обратите внимание, что обратная косая черта должна экранироваться. К сожалению, в Java нет способа отменить
экранирование для более короткой записи Windows-путей.

Объекты класса Path являются неизменяемыми. Все операции с путями возвращают новые объекты Path.

Строковое представление

У класса Path есть вполне привычный метод toString(), возвращающий представление пути в виде строки, используя
системный разделитель компонентов пути.

Path path = Paths.get("C:\windows\system32");
System.out.println(path);
// Или, что то же самое:
// System.out.println(path.toString())

Результат:

Абсолютные и относительные пути

Приведённый выше пример пути является абсолютным путём, потому что он начинается с корня ФС. Абсолютный путь всегда
однозначно идентифицирует элемент ФС, независимо от того, какой каталог является текущим каталогом программы.

В Unix абсолютные пути начинаются с косой черты, обозначающей корень файловой системы, а в Windows — с буквы
диска. Например, следующие два пути являются абсолютными:

Path unixAbsPath = Paths.get("/usr/bin/firefox");
Path winAbsPath = Paths.get("C:\Program Files\Mozilla Firefox\firefox.exe");

Относительные пути — это пути, ведущие отсчёт от какого-то каталога. По умолчанию при выполнении операций ФС
над относительными путями они разрешаются относительно текущего каталога (current directory), также называемого
рабочим каталогом (working directory). Метод toAbsolutePath() позволяет преобразовать относительный путь в
абсолютный, при этом он разрешается относительно текущего каталога.

Пусть в каталоге /home/user/java лежит файл AbsolutePath.class, откомпилированный из такого файла:

import java.nio.file.Path;
import java.nio.file.Paths;

public class AbsolutePath {
	public static void main(String[] args) {
		Path relPath = Paths.get("lib/opencsv.jar");
		Path absPath = relPath.toAbsolutePath();
		System.out.println(absPath);
	}
}

Тогда мы получим такой результат при запуске этой программы из командной строки (напомним, что команда cd
устанавливает текущий каталог):

$ cd /home/user/java
$ java AbsolutePath
/home/user/java/lib/opencsv.jar
$ cd /tmp
$ java -cp /home/user/java AbsolutePath
/tmp/lib/opencsv.jar

При задании относительных путей из соображений переносимости нежелательно использовать разделитель путей Windows ,
если только не известно точно, что программа будет запускаться только под Windows. Windows понимает разделитель путей
Unix /, а вот обратное неверно. Ещё правильнее использовать статический метод Paths.get с несколькими параметрами,
чтобы не завязываться на конкретный платформозависимый разделитель, а в случае необходимости всё-таки получить этот
разделитель в виде строки можно воспользоваться методом FileSystem.getSeparator:

System.out.println(FileSystem.getDefault().getSeparator());
// Печатает / под Unix и  под Windows

Для преобразования относительного пути в абсолютный относительно не текущего каталога, а какого-то другого, можно
воспользоваться методом resolve. Его нужно вызвать у того пути, относительно которого мы разрешаем относительный путь.
У метода resolve есть две версии: одна принимает Path, а вторая принимает String и рассматривает эту строку как
путь, который предстоит разрешить.

Path resolve(Path other)

Path resolve(String other)

Например:

Path configDir = Paths.get("/etc");
System.out.println(configDir.resolve("passwd"));
// /etc/passwd
Path apacheConf = Paths.get("apache2", "apache2.conf");
System.out.println(configDir.resolve(apacheConf));
// /etc/apache2/apache2.conf

Обратную задачу решает метод relativize, превращающий переданный параметром абсолютный путь в относительный
относительно того пути, у которого этот метод вызывается.

Path relativize(Path other)

Например:

Path homeDir = Paths.get("/home/user");
Path movie = Paths.get("/home/user/Videos/JavaLesson.mkv");
System.out.println(homeDir.relativize(movie));
// Videos/JavaLesson.mkv

Переход вверх и вниз по иерархии ФС

Метод getParent возвращает родительский элемент ФС (как правило, каталог), или null, если такового не существует.

Path getParent()

Например:

System.out.println(Paths.get("C:\windows").getParent());
// C:
System.out.println(Paths.get("C:").getParent());
// null

А метод resolve можно использовать не только для абсолютизации путей, но и для получения пути к какому-либо элементу
каталога или какого-то его подкаталога ещё ниже по иерархии ФС:

Paths.get("C:\windows").resolve("explorer.exe")
// C:windowsexplorer.exe
Paths.get("C:\windows").resolve("system32\user32.dll")
// C:windowssystem32user32.dll

Есть также метод resolveSibling, позволяющий получить “сестринский” элемент ФС, то есть разрешающий переданный путь
относительно родительского элемента ФС.

Path resolveSibling(Path other)

Path resolveSibling(String other)

Например, он позволяет получить путь к другому файлу в том же каталоге:

Path dll = Paths.get("C:\windowssystem32\user32.dll")
System.out.println(dll.resolveSibling("kernel32.dll")
// C:windowssystem32kernel32.dll

Доступ к компонентам пути

Методы getNameCount и getName позволяют пройтись по всем компонентам пути, представленного объектом Path. Эти
компоненты сами имеют тип Path.

int getNameCount()

Path getName(int index)

Например:

Path path = Paths.get("C:\windowsexplorer.exe");

for (int i = 0; i < path.getNameCount(); i++) {
	System.out.println(path.getName(i));
}

Результат:

Кроме того, класс Path реализует интерфейс Iterable<Path> и, следовательно, поддержку цикла for-each, поэтому то же
самое делает и такой код:

for (Path component: path) {
	System.out.println(component);
}

и даже

path.forEach(System.out::println);

Получение имени файла и каталога

Метод getFileName возвращает путь из одного компонента, соответствующего последнему компоненту исходного пути. Обычно
это имя файла или другого элемента ФС, на который указывает объект Path. Обратите внимание, что этот метод возвращает
Path, а не String.

Path getFileName()

Например:

Paths.get("/home/user/Pictures/kitty.jpg").getFileName()
// kitty.jpg
Paths.get("C:\gamesWorld of Warcraft").getFileName()
// World of Warcraft

Как мы знаем, получить путь к каталогу, в котором находится файл, можно с помощью getParent:

Paths.get("/home/user/Pictures/kitty.jpg").getParent()
// /home/user
Paths.get("C:\gamesWorld of Warcraft").getParent()
// C:games

Работа с расширениями

К сожалению, класс Path сам по себе не предоставляет удобных способов работы с расширениями. В некотором смысле это
логично, ведь понятие расширения существует только для приложений, работающих с файлами, а для самой ФС это всего лишь
часть имени файла. Чтобы отделить расширение, придётся работать с именем файла как со строкой.

Прежде всего эту строку нужно получить:

String fileNameStr = path.getFileName().toString();

После чего работать с расширениями можно обычными строковыми методами:

boolean isPng = fileNameStr.toLowerCase().endsWith(".png");

Обратите внимание на вызов toLowerCase. Это гарантирует, что мы проверим имя файла на нужное расширение в любом
регистре (.png, .PNG, .Png и т.д.).

У интерфейса Path тоже есть метод endsWith, но он проверяет, заканчивается ли путь данным компонентом пути, а не
заканчивается ли строка имени файла данной строкой. Не путайте!

Paths.get("/home/user/report.txt").endsWith("report.txt")  // true
Paths.get("report.txt").endsWith(".txt")  // false
Paths.get("report.txt").toString().endsWith(".txt")  // true

Наконец, можно написать свой метод, который возвращает расширение имени файла или пустую строку, если у имени файла
нет расширения:

public String getExtension(Path path) {
	String fileNameStr = path.getFileName().toString();
	int lastDot = fileNameStr.lastIndexOf('.');
	
	if (lastDot == -1) {
		return "";
	} else {
		return fileNameStr.substring(lastDot + 1);
	}
}

Взаимодействие со старыми API

Интерфейс Path появился в Java 7. Старые API, спроектированные для Java 6 и ниже, обычно используют вместо него более
старый класс File, существовавший аж в Java 1.0. Он менее удобен, чем Path, потому что поддерживает только
стандартную ФС и нарушает принцип единственности ответственности, сочетая в себе методы для синтаксической манипуляции
путями и методы доступа к ФС.

Если нужно передать объект Path в старое API, используйте метод toFile:

File toFile()

И, получая объекты File из старого API, преобразуйте их в Path:

Path toPath()

К примеру, класс ImageIO, отвечающий за загрузку, сохранение и преобразование изображений, к сожалению, так и не был
обновлён для поддержки параметров типа Path. Вот так с помощью ImageIO можно преобразовать любой поддерживаемый
формат изображений в формат PNG:

Path source = Paths.get("/home/user/Pictures/diagram.bmp");
BufferedImage image = ImageIO.read(source.toFile());

Path dest = Paths.get("/home/user/Pictures/diagram.png");
ImageIO.write(image, "bmp", dest.toFile());

Code :

public class JavaApplication {
  public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
  }
}

This will print the absolute path of the current directory from where your application was initialized.


Explanation:

From the documentation:

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.

Anish B.'s user avatar

Anish B.

9,0073 gold badges19 silver badges41 bronze badges

answered Sep 29, 2011 at 21:12

Anuj Patel's user avatar

Anuj PatelAnuj Patel

17.1k3 gold badges29 silver badges57 bronze badges

12

See: Path Operations (The Java™ Tutorials > Essential Classes > Basic I/O).

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.

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);

This outputs:

Current absolute 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.

Mohammad Rifat Arefin's user avatar

answered Apr 11, 2013 at 17:10

geoO's user avatar

geoOgeoO

5,3921 gold badge13 silver badges9 bronze badges

5

The following works on Java 7 and up (see here for documentation).

import java.nio.file.Paths;

Paths.get(".").toAbsolutePath().normalize().toString();

jasonmp85's user avatar

jasonmp85

6,7392 gold badges25 silver badges41 bronze badges

answered Mar 12, 2014 at 12:03

Dmitry Bespalov's user avatar

Dmitry BespalovDmitry Bespalov

5,1693 gold badges25 silver badges33 bronze badges

6

This will give you the path of your current working directory:

Path path = FileSystems.getDefault().getPath(".");

And this will give you the path to a file called “Foo.txt” in the working directory:

Path path = FileSystems.getDefault().getPath("Foo.txt");

Edit :
To obtain an absolute path of current directory:

Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();

* Update *
To get current working directory:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();

Loyal Service's user avatar

answered Sep 15, 2017 at 20:01

Mark's user avatar

MarkMark

2,20418 silver badges26 bronze badges

4

Java 11 and newer

This solution is better than others and more portable:

Path cwd = Path.of("").toAbsolutePath();

Or even

String cwd = Path.of("").toAbsolutePath().toString();

answered Jun 25, 2018 at 16:29

freedev's user avatar

freedevfreedev

25k8 gold badges108 silver badges124 bronze badges

4

This is the solution for me

File currentDir = new File("");

answered May 28, 2013 at 23:09

user2430452's user avatar

user2430452user2430452

3873 silver badges3 bronze badges

5

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.

answered Feb 2, 2011 at 5:39

Paul Wagland's user avatar

Paul WaglandPaul Wagland

27.4k10 gold badges52 silver badges74 bronze badges

1

this.getClass().getClassLoader().getResource("").getPath()

Spudley's user avatar

Spudley

165k39 gold badges231 silver badges306 bronze badges

answered May 15, 2013 at 13:50

Peter De Winter's user avatar

Peter De WinterPeter De Winter

1,1732 gold badges15 silver badges27 bronze badges

3

generally, as a File object:

File getCwd() {
  return new File("").getAbsoluteFile();
}

you may want to have full qualified string like “D:/a/b/c” doing:

getCwd().getAbsolutePath()

answered Jan 26, 2015 at 12:13

comeGetSome's user avatar

comeGetSomecomeGetSome

1,91319 silver badges20 bronze badges

3

I’m on Linux and get same result for both of these approaches:

@Test
public void aaa()
{
    System.err.println(Paths.get("").toAbsolutePath().toString());

    System.err.println(System.getProperty("user.dir"));
}

Paths.get("") docs

System.getProperty("user.dir") docs

rink.attendant.6's user avatar

answered Dec 28, 2013 at 3:11

Bohdan's user avatar

BohdanBohdan

16.4k15 gold badges73 silver badges68 bronze badges

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:

String myCurrentDir = System.getProperty("user.dir")
            + File.separator
            + System.getProperty("sun.java.command")
                    .substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
                    .replace(".", File.separator);
    System.out.println(myCurrentDir);

Note: This code is only tested in Windows with Oracle JRE.

answered Sep 27, 2012 at 10:09

JSS's user avatar

JSSJSS

2,0511 gold badge20 silver badges26 bronze badges

4

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.

Paths.get("").toAbsolutePath().toString();

System.getProperty("user.dir");

If your Class with main would be called MainClass, then try:

MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();

This will return a String with absolute path of the jar file.

answered Dec 17, 2015 at 22:29

Jan Povolný's user avatar

2

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

answered Dec 25, 2015 at 14:42

SijeDeHaan's user avatar

SijeDeHaanSijeDeHaan

1752 silver badges2 bronze badges

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.


Warnings!

  • 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:

🍂..

//The class from which i called this was the class `Main`
String path = getBasePathForClass(Main.class);
String applicationPath=  new File(path + "application.jar").getAbsolutePath();


System.out.println("Directory Path is : "+applicationPath);

//Your know try catch here
//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2#@!$%^^&()` 
ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath);
builder.redirectErrorStream(true);
Process process = builder.start();

//...code

🍂getBasePathForClass(Class<?> classs):

    /**
     * Returns the absolute path of the current directory in which the given
     * class
     * file is.
     * 
     * @param classs
     * @return The absolute path of the current directory in which the class
     *         file is.
     * @author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]
     */
    public static final String getBasePathForClass(Class<?> classs) {

        // Local variables
        File file;
        String basePath = "";
        boolean failed = false;

        // Let's give a first try
        try {
            file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

            if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
                basePath = file.getParent();
            } else {
                basePath = file.getPath();
            }
        } catch (URISyntaxException ex) {
            failed = true;
            Logger.getLogger(classs.getName()).log(Level.WARNING,
                    "Cannot firgue out base path for class with way (1): ", ex);
        }

        // The above failed?
        if (failed) {
            try {
                file = new File(classs.getClassLoader().getResource("").toURI().getPath());
                basePath = file.getAbsolutePath();

                // the below is for testing purposes...
                // starts with File.separator?
                // String l = local.replaceFirst("[" + File.separator +
                // "/\\]", "")
            } catch (URISyntaxException ex) {
                Logger.getLogger(classs.getName()).log(Level.WARNING,
                        "Cannot firgue out base path for class with way (2): ", ex);
            }
        }

        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbeans
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    }

answered Nov 20, 2016 at 17:04

GOXR3PLUS's user avatar

GOXR3PLUSGOXR3PLUS

6,7879 gold badges42 silver badges92 bronze badges

2

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

public static final String getBasePathForClass(Class<?> clazz) {
    File file;
    try {
        String basePath = null;
        file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
            basePath = file.getParent();
        } else {
            basePath = file.getPath();
        }
        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbean
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    } catch (URISyntaxException e) {
        throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
    }
}

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 😀

Best,

answered Apr 16, 2015 at 4:39

bachden's user avatar

bachdenbachden

4413 silver badges9 bronze badges

2

For Java 11 you could also use:

var path = Path.of(".").toRealPath();

answered Mar 24, 2021 at 17:52

Volodya Lombrozo's user avatar

Volodya LombrozoVolodya Lombrozo

2,1121 gold badge14 silver badges32 bronze badges

This is a very confuse topic, and we need to understand some concepts before providing a real solution.

  1. The File, and NIO File Api approaches with relative paths "" or "." uses internally the system parameter "user.dir" value to determine the return location.

  2. The "user.dir” value is based on the USER working directory, and the behavior of that value depends on the operative system, and the way the jar is executed.

  3. For example, executing a JAR from Linux using a File Explorer (opening it by double click) will set user.dir with the user home directory, regardless of the location of the jar. If the same jar is executed from command line, it will return the jar location, because each cd command to the jar location modified the working directory.

Having said that, the solutions using Java NIO, Files or "user.dir" property will work for all the scenarios in the way the "user.dir" has the correct value.

String userDirectory = System.getProperty("user.dir");
String userDirectory2 = new File("").getAbsolutePath();
String userDirectory3 = Paths.get("").toAbsolutePath().toString();

We could use the following code:

new File(MyApp.class.getProtectionDomain()
                     .getCodeSource()
                     .getLocation()
                     .toURI().getPath())
     .getParent();

to get the current location of the executed JAR, and personally I used the following approach to get the expected location and overriding the "user.dir" system property at the very beginning of the application. So, later when the other approaches are used, I will get the expected values always.

More details here -> https://blog.adamgamboa.dev/getting-current-directory-path-in-java/

    public class MyApp {
      
      static {
        //This static block runs at the very begin of the APP, even before the main method.
        try{
          File file = new File(MyApp.class.getProtectionDomain().getCodeSource()
                           .getLocation().toURI().getPath());
          String basePath = file.getParent();
          //Overrides the existing value of "user.dir"
          System.getProperties().put("user.dir", basePath);
        }catch(URISyntaxException ex){
          //log the error
        }
      }
     
      public static void main(String args []){
        //Your app logic
        
        //All these approaches should return the expected value
        //regardless of the way the jar is executed.
        String userDirectory = System.getProperty("user.dir");
        String userDirectory2 = new File("").getAbsolutePath();
        String userDirectory3 = Paths.get("").toAbsolutePath().toString();
      }
    }

I hope this explanation and details are helpful to others…

answered Jun 20, 2022 at 17:22

Adam M. Gamboa G.'s user avatar

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

Something like

java -D com.mycompany.workingDir="%0"

That’s not quite right, but you get the idea. Then System.getProperty("com.mycompany.workingDir")

L Joey's user avatar

L Joey

1552 silver badges8 bronze badges

answered Feb 2, 2011 at 5:37

MJB's user avatar

MJBMJB

9,3126 gold badges34 silver badges49 bronze badges

3

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…

  public static void callJVisualVM() {
    System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
    //next search current jdk/jre
    String jre_root = null;
    String start = "vir";
    try {
        java.lang.management.RuntimeMXBean runtime =
                java.lang.management.ManagementFactory.getRuntimeMXBean();
        String jvmName = runtime.getName();
        System.out.println("JVM Name = " + jvmName);
        long pid = Long.valueOf(jvmName.split("@")[0]);
        System.out.println("JVM PID  = " + pid);
        Runtime thisRun = Runtime.getRuntime();
        jre_root = System.getProperty("java.home");
        System.out.println("jre_root:" + jre_root);
        start = jre_root.concat("\..\bin\jvisualvm.exe " + "--openpid " + pid);
        thisRun.exec(start);
    } catch (Exception e) {
        System.getProperties().list(System.out);
        e.printStackTrace();
    }
}

answered May 18, 2020 at 0:54

Tonecops's user avatar

1

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:Windowssystem32, 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:Windowssystem32, 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.

answered Sep 15, 2020 at 22:20

Ted's user avatar

2

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..

The code

import java.io.File;

public class Find_this_dir {

    public static void main(String[] args) {

//some sort of a bug in java path is correct but file dose not exist
        File this_dir = new File("");

//but these both commands work too to get current dir        
//      File this_dir_2 = new File(this_dir.getAbsolutePath());
        File this_dir_2 = new File(new File("").getAbsolutePath());

        System.out.println("new File(" + """" + ")");
        System.out.println(this_dir.getAbsolutePath());
        System.out.println(this_dir.exists());
        System.out.println("");
        System.out.println("new File(" + "new File(" + """" + ").getAbsolutePath()" + ")");
        System.out.println(this_dir_2.getAbsolutePath());
        System.out.println(this_dir_2.exists());
    }
}

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

answered Jan 25, 2021 at 6:53

Avon97's user avatar

Avon97Avon97

4712 bronze badges

My favorite method is to get it from the system environment variables attached to the current running process. In this case, your application is being managed by the JVM.

String currentDir = System.getenv("PWD");
/*
 /home/$User/Documents/java
*/

To view other environment variables that you might find useful like, home dir, os version ……..

//Home directory
String HomeDir = System.getEnv("HOME");


//Outputs for unix
/home/$USER

//Device user
String user = System.getEnv("USERNAME");


//Outputs for unix
$USER

The beautiful thing with this approach is that all paths will be resolved for all types of OS platform

Mainz007's user avatar

Mainz007

5335 silver badges16 bronze badges

answered May 31, 2021 at 10:10

Andrew Mititi's user avatar

3

You might use new File("./"). This way isDirectory() returns true (at least on Windows platform). On the other hand new File("") isDirectory() returns false.

answered Jan 7, 2022 at 16:58

Wortig's user avatar

WortigWortig

8322 gold badges11 silver badges35 bronze badges

Not exactly sure what you’re trying to accomplish but the above answers work on the current working directory where you are asking from not from where the program is actually located.

For instance:

$> mkdir -p /tmp/paths/check 
$> cat > /tmp/paths/check/GetPath.java
import java.nio.file.Paths;
import java.nio.file.FileSystems;

public class GetPath {
// Note: these methods work slightly differently, the last two will provide the working dir
// for where this program was launched, while the first will get the cwd from where this
// program resides.
public static void main(String[] args) {
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println("Thread rootPath is "+rootPath);
        System.out.println("System property user.dir is "+System.getProperty("user.dir"));
        System.out.println("NIO Paths way is "+Paths.get("").toAbsolutePath());
        System.out.println("NIO FileSystems way is "+FileSystems.getDefault().getPath("").toAbsolutePath());
}
}

Then if you run it from /tmp, you will see:

$> cd /tmp/paths/check; javac GetPath.java
$> cd /tmp
$> java -cp paths/check GetPath
Thread rootPath is /tmp/paths/check/
system property user.dir is /tmp
NIO Paths way is/tmp
NIO FileSystems way is/tmp

So the first method using the ContextClassLoader may be more appropriate depending on what you are trying to accomplish.

answered Mar 2 at 23:39

Adam D.'s user avatar

Adam D.Adam D.

1511 silver badge4 bronze badges

None of the answers posted here worked for me. Here is what did work:

java.nio.file.Paths.get(
  getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);

Edit: The final version in my code:

URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
    myURI = myURL.toURI();
} catch (URISyntaxException e1) 
{}
return java.nio.file.Paths.get(myURI).toFile().toString()

answered Mar 31, 2015 at 19:35

VenerableAgents's user avatar

VenerableAgentsVenerableAgents

6471 gold badge8 silver badges16 bronze badges

1

System.getProperty("java.class.path")

answered Jan 3, 2015 at 23:10

Marko Stojkovic's user avatar

Marko StojkovicMarko Stojkovic

3,2054 gold badges19 silver badges20 bronze badges

В Java для NIO Путь мы можем использовать путь.toAbsolutePath() чтобы получить путь к файлу; Для устаревшего ввода-вывода File мы можем использовать file.getAbsolutePath() для получения пути к файлу.

Для символических ссылок или путь к файлу содержит . или .. , мы можем использовать path.torealpath() или file.getCanonicalPath() , чтобы получить реальный путь к файлу.

Ниже приведено отображение файла и Путь .

  1. файл.getAbsolutePath() <=> путь.Путь к абсолюту()
  2. файл.getCanonicalPath() <=> путь.torealpath()
  3. файл.getParent() <=> путь.getParent()

1. Получить путь к файлу файла (путь NIO).

Для java.nio.файла. Путь , мы можем использовать следующие API-интерфейсы для получения пути к файлу файла.

  1. путь.Путь к абсолюту() – Полный путь к файлу.
  2. путь.Тореальный путь()) – Для символических ссылок или разрешения . или .. символы в имени пути, по умолчанию по ссылке.
  3. путь.getParent() – Получить родительский каталог пути.

1.1 Путь = /home/mkyong/test/file.txt

Path path = Paths.get("/home/mkyong/test/file.txt");

path                      : /home/mkyong/test/file.txt
path.toAbsolutePath()     : /home/mkyong/test/file.txt
path.getParent()          : /home/mkyong/test
path.toRealPath()         : /home/mkyong/test/file.txt

1.2 Путь = file.txt , файл ссылается на текущий рабочий каталог + file.txt .

Path path = Paths.get("file.txt");

path                      : file.txt
path.toAbsolutePath()     : /home/mkyong/projects/core-java/java-io/file.txt
path.getParent()          : null
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/file.txt

1.3 Путь = /главная/mkyong/тест/программная ссылка , символическая ссылка.

$ ln -s
  /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java
  /home/mkyong/test/soft-link
Path path = Paths.get("/home/mkyong/test/soft-link");

path                      : /home/mkyong/test/soft-link
path.toAbsolutePath()     : /home/mkyong/test/soft-link
path.getParent()          : /home/mkyong/test
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java

1.4 Путь = /home/mkyong/test/../hello.txt

Path path = Paths.get("/home/mkyong/test/../hello.txt");

path                      : /home/mkyong/test/../hello.txt
path.toAbsolutePath()     : /home/mkyong/test/../hello.txt
path.getParent()          : /home/mkyong/test/..
path.toRealPath()         : /home/mkyong/hello.txt

1.5 Ниже приведен полный пример Java для получения пути к файлу разных Путь .

package com.mkyong.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetFilePath1 {

    public static void main(String[] args) {

        // full path
        Path path1 = Paths.get("/home/mkyong/test/file.txt");
        System.out.println("n[Path] : " + path1);
        printPath(path1);

        // file name
        Path path2 = Paths.get("file.txt");
        System.out.println("n[Path] : " + path2);
        printPath(path2);

        // soft or symbolic link
        Path path3 = Paths.get("/home/mkyong/test/soft-link");
        System.out.println("n[Path] : " + path3);
        printPath(path3);

        // a path contains `..`
        Path path4 = Paths.get("/home/mkyong/test/../hello.txt");
        System.out.println("n[Path] : " + path4);
        printPath(path4);

    }

    static void printPath(Path path) {

        System.out.printf("%-25s : %s%n", "path", path);
        System.out.printf("%-25s : %s%n", "path.toAbsolutePath()",
                                                path.toAbsolutePath());
        System.out.printf("%-25s : %s%n", "path.getParent()", path.getParent());
        System.out.printf("%-25s : %s%n", "path.getRoot()", path.getRoot());

        try {

            if (Files.notExists(path)) {
                return;
            }

            // default, follow symbolic link
            System.out.printf("%-25s : %s%n", "path.toRealPath()",
                                                  path.toRealPath());
            // no follow symbolic link
            System.out.printf("%-25s : %s%n", "path.toRealPath(nofollow)",
                path.toRealPath(LinkOption.NOFOLLOW_LINKS));

            // alternative to check isSymbolicLink
            /*if (Files.isSymbolicLink(path)) {
                Path link = Files.readSymbolicLink(path);
                System.out.println(link);
            }*/

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Выход

[Path] : /home/mkyong/test/file.txt
path                      : /home/mkyong/test/file.txt
path.toAbsolutePath()     : /home/mkyong/test/file.txt
path.getParent()          : /home/mkyong/test
path.getRoot()            : /
path.toRealPath()         : /home/mkyong/test/file.txt
path.toRealPath(nofollow) : /home/mkyong/test/file.txt

[Path] : file.txt
path                      : file.txt
path.toAbsolutePath()     : /home/mkyong/projects/core-java/java-io/file.txt
path.getParent()          : null
path.getRoot()            : null
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/file.txt
path.toRealPath(nofollow) : /home/mkyong/projects/core-java/java-io/file.txt

[Path] : /home/mkyong/test/soft-link
path                      : /home/mkyong/test/soft-link
path.toAbsolutePath()     : /home/mkyong/test/soft-link
path.getParent()          : /home/mkyong/test
path.getRoot()            : /
path.toRealPath()         : /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java
path.toRealPath(nofollow) : /home/mkyong/test/soft-link

[Path] : /home/mkyong/test/../hello.txt
path                      : /home/mkyong/test/../hello.txt
path.toAbsolutePath()     : /home/mkyong/test/../hello.txt
path.getParent()          : /home/mkyong/test/..
path.getRoot()            : /
path.toRealPath()         : /home/mkyong/hello.txt
path.toRealPath(nofollow) : /home/mkyong/hello.txt

2. Получить путь к файлу файла (устаревший файл)

Для устаревшего ввода-вывода java.io . Файл , мы можем использовать следующие API-интерфейсы для получения пути к файлу.

  1. файл.getAbsolutePath() = путь.Путь к абсолюту()
  2. файл.getCanonicalPath() = путь.torealpath()
  3. файл.getParent() = путь.getParent()
package com.mkyong.io.howto;

import java.io.File;
import java.io.IOException;

public class GetFilePath2 {

    public static void main(String[] args) {

        // full file path
        File file1 = new File("/home/mkyong/test/file.txt");
        System.out.println("[File] : " + file1);
        printFilePath(file1);

        // a file name
        File file2 = new File("file.txt");
        System.out.println("n[File] : " + file2);
        printFilePath(file2);

        // a soft or symbolic link
        File file3 = new File("/home/mkyong/test/soft-link");
        System.out.println("n[File] : " + file3);
        printFilePath(file3);

        // a file contain `..`
        File file4 = new File("/home/mkyong/test/../hello.txt");
        System.out.println("n[File] : " + file4);
        printFilePath(file4);

    }

    // If a single file name, not full path, the file refer to
    // System.getProperty("user.dir") + file
    static void printFilePath(File file) {
        // print File = print file.getPath()
        System.out.printf("%-25s : %s%n", "file.getPath()", file.getPath());
        System.out.printf("%-25s : %s%n", "file.getAbsolutePath()",
                                              file.getAbsolutePath());
        try {
            System.out.printf("%-25s : %s%n", "file.getCanonicalPath()",
                                                file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.printf("%-25s : %s%n", "Parent Path", getParentPath(file));
    }

    // if unable to get parent, try substring to get the parent folder.
    private static String getParentPath(File file) {
        if (file.getParent() == null) {
            String absolutePath = file.getAbsolutePath();
            return absolutePath.substring(0,
                          absolutePath.lastIndexOf(File.separator));
        } else {
            return file.getParent();
        }
    }

}

Выход

[File] : /home/mkyong/test/file.txt
file.getPath()            : /home/mkyong/test/file.txt
file.getAbsolutePath()    : /home/mkyong/test/file.txt
file.getCanonicalPath()   : /home/mkyong/test/file.txt
Parent Path               : /home/mkyong/test

[File] : file.txt
file.getPath()            : file.txt
file.getAbsolutePath()    : /home/mkyong/projects/core-java/java-io/file.txt
file.getCanonicalPath()   : /home/mkyong/projects/core-java/java-io/file.txt
Parent Path               : /home/mkyong/projects/core-java/java-io

[File] : /home/mkyong/test/soft-link
file.getPath()            : /home/mkyong/test/soft-link
file.getAbsolutePath()    : /home/mkyong/test/soft-link
file.getCanonicalPath()   : /home/mkyong/projects/core-java/java-io/src/main/java/com/mkyong/io/howto/GetFilePath.java
Parent Path               : /home/mkyong/test

[File] : /home/mkyong/test/../hello.txt
file.getPath()            : /home/mkyong/test/../hello.txt
file.getAbsolutePath()    : /home/mkyong/test/../hello.txt
file.getCanonicalPath()   : /home/mkyong/hello.txt
Parent Path               : /home/mkyong/test/..

Скачать Исходный Код

$клон git $клон git

$cd java-ввод-вывод

Рекомендации

  • Файл JavaDoc
  • Путь JavaDoc
  • Текущий рабочий каталог Java

Оригинал: “https://mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/”


  • Метки


    file, filepath, path

Для получения полного пути к файлу в Java применяется метод getAbsolutePath() класса File. Этот метод возвращает полный путь к файлу в формате [каталог] + [файл], где [каталог] — полный путь к родительскому каталогу, а [файл] — имя файла.

Пример 1. Получение полного пути к файлу.

Ниже представлен код программы, который выводит на стандартный вывод полный путь к файлу.

package ru.j4web.examples.java.io;

import java.io.File;

public class FileAbsolutePathExample {

    private static final String FILENAME = "c:ProjectsJ4Web.RuSrc"
            + "JavaIOFileAbsolutePathExamplemyDocument.txt";
    
    public static void main(String[] args) {
        final File file = new File(FILENAME);
        if(file.exists()) {
            System.out.println("Полный путь к файлу: "
                    + file.getAbsolutePath());
        }
    }
}

Пример 2. Получение родительского каталога.

Ниже представлен код программы, которая выводит на стандартный вывод полный путь к родительскому каталогу файла.

package ru.j4web.examples.java.io;

import java.io.File;

public class ParentFolderAbsolutePathExample {

    private static final String FILENAME = "c:ProjectsJ4Web.RuSrc"
            + "JavaIOParentFolderAbsolutePathExamplemyDocument.txt";

    public static void main(String[] args) {
        final File file = new File(FILENAME);
        System.out.println("Полный путь к файлу: " + file.getAbsolutePath());
        if (file.exists()) {
            final File parentFolder = new File(file.getAbsolutePath()
                    .substring(0, file.getAbsolutePath().lastIndexOf(
                                    File.separator)));
            System.out.println("Полный путь к родительскому каталогу: "
                    + parentFolder.getAbsolutePath());
        } else {
            System.out.println("Файл не существует.");
        }
    }
}

Полезная информация

  • Javadoc класса File
  • Javadoc класса String

Как получить путь к файлу в Java

File.getAbsolutePath() даст вам полный полный путь к файлу (путь к файлу + имя файла).

Например,

File file = File("C:\abcfolder\textfile.txt");
System.out.println("Path : " + file.getAbsolutePath());

Будет отображен полный путь: «Path : C:abcfoldertextfile.txt».

В большинстве случаев вам может потребоваться получить только путь к файлу «C:abcfolder». С помощью методовsubstring() иlastIndexOf() вы можете легко извлечь путь к файлу:

File file = File("C:\abcfolder\textfile.txt");
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.
    substring(0,absolutePath.lastIndexOf(File.separator));

Получить пример пути к файлу

В этом примере он создает временный файл и распечатывает путь к нему.

package com.example.file;

import java.io.File;
import java.io.IOException;

public class AbsoluteFilePathExample
{
    public static void main(String[] args)
    {
        try{

            File temp = File.createTempFile("i-am-a-temp-file", ".tmp" );

            String absolutePath = temp.getAbsolutePath();
            System.out.println("File path : " + absolutePath);

            String filePath = absolutePath.
                     substring(0,absolutePath.lastIndexOf(File.separator));

            System.out.println("File path : " + filePath);

        }catch(IOException e){

            e.printStackTrace();

        }

    }
}

Результат

File path : C:UsersexampleAppDataLocalTempi-am-a-temp-file69424.tmp
File path : C:UsersexampleAppDataLocalTemp

Ссылка

  1. File.getAbsolutePath() documentation

  2. Документация String substring () и lastIndexOf ()

Добавить комментарий