How to get the working directory of a running Java process?

The original post is the one that most people posted

Here is the code that I have already tried to do with

String workingDirectory = "/home"; String command = "cd ../"; ProcessBuilder pb = new ProcessBuilder(new String[] { "cmd", "/c", command }); pb.directory(new File(workingDirectory)); pb.redirectErrorStream(true); Process process = pb.start(); // Some time later once the process has been closed workingDirectory = pb.directory().getAbsolutePath(); System.out.println("Path: " + workingDirectory); 

This does not work, as soon as it ends, it exits with the same working directory.

Any help would be greatly appreciated, it would be very helpful to think to know.

To be more specific, I am looking to find a working directory for a dynamically created process in Java, for example, in the above snippet. This is important because, for example, the predefined command above, working directories can sometimes change, I would like to save any changes in memory for later use.

I found a way to do this and it seems to work without problems

This is how I handle the incoming working directory

 public int osType = 1; // This is for Windows (0 is for Linux) public boolean isValidPath(String path) { try { Paths.get(new File(path).getAbsolutePath()); } catch (InvalidPathException | NullPointerException ex) { return false; } return true; } public String tracePath(String path) { try { if (!path.contains("%%") && !isValidPath(path)) return null; if (path.contains("%%")) path = path.substring(path.indexOf("%%")); int lastIndex = -1; char filesystemSlash = ' '; if (osType == 0) filesystemSlash = '/'; if (osType == 1) filesystemSlash = '\\'; if (osType == 0) path = path.substring(path.indexOf(filesystemSlash)); if (osType == 1) path = path.substring(path.indexOf(filesystemSlash) - 2); String tmp = path; boolean broken = true; while (!isValidPath(tmp)) { int index = tmp.lastIndexOf(filesystemSlash); if (lastIndex == index) { broken = false; break; } tmp = tmp.substring(0, index); lastIndex = index; } if (broken && lastIndex != -1) { tmp = path.substring(0, lastIndex); } return tmp; } catch (StringIndexOutOfBoundsException ex) { return null; } } 

Here is a method to ignore path issues (not using it)

 public boolean setDirectory(ProcessBuilder pb, String path) { try { pb.directory(new File(new File(path).getAbsolutePath())); return true; } catch (Exception ex) { return false; } } 

Now this is how I start the process for Windows or Linux

 File file = null; if (osType == 1) { ProcessBuilder pb = new ProcessBuilder(new String[] { "cmd", "/c", command + " & echo %% & cd" }); pb.redirectErrorStream(true); if (!workingDirectory.equals("")) setDirectory(pb, workingDirectory); process = pb.start(); } else if (osType == 0) { file = new File("script.sh"); FileWriter writer = new FileWriter(file, false); writer.append(command + " && echo %% && pwd"); writer.flush(); writer.close(); ProcessBuilder pb = new ProcessBuilder(new String[] { "bash", System.getProperty("user.dir") + "/script.sh" }); pb.redirectErrorStream(true); if (!workingDirectory.equals("")) setDirectory(pb, workingDirectory); process = pb.start(); } else return; 

Finally, here is a loop that manages the process and working directory

 while (process.isAlive() || process.getInputStream().available() > 0) { byte[] returnBytes = new byte[1024]; process.getInputStream().read(returnBytes); char[] arr = new String(returnBytes).trim().toCharArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { char c = arr[i]; if (Character.isDefined(c)) sb.append(c); } String response = sb.toString(); if (!response.equals("")) { String path = tracePath(response.trim().replace("\n", "").replace("\r", "")); if (path != null && osType == 1) { if (Paths.get(path).toFile().exists()) workingDirectory = path; } else if (path != null && osType == 0) { if (Paths.get(path).toFile().exists()) workingDirectory = path; } client.sendMessage(response + '\r' + '\n'); } } if (file != null) file.delete(); 

Here is the result of getting the team on the site

 Connecting.. Connected. Success. You have been connected -> Speentie bash -c pwd /root/hardsceneServer/remoteServer %% /root/hardsceneServer/remoteServer bash -c cd .. %% /root/hardsceneServer bash -c pwd /root/hardsceneServer %% /root/hardsceneServer bash -c dir ircServer nohup.out remoteServer start.sh start1.sh start2.sh %% /root/hardsceneServer bash -c cd ircServer %% /root/hardsceneServer/ircServer bash -c dir HardScene.jar hardscene_banned.properties start.sh hardscene.properties nohup.out %% /root/hardsceneServer/ircServer 
+6
source share
7 answers

Are you looking for something like this?

 System.out.println("Current working directory: " + System.getProperty("user.dir")); System.out.println("Changing working directory..."); // changing the current working directory System.setProperty("user.dir", System.getProperty("user.dir") + "/test/"); // print the new working directory path System.out.println("Current working directory: " + System.getProperty("user.dir")); // create a new file in the current working directory File file = new File(System.getProperty("user.dir"), "test.txt"); if (file.createNewFile()) { System.out.println("File is created at " + file.getCanonicalPath()); } else { System.out.println("File already exists."); } 

It outputs:

 Current working directory: /Users/Wasi/NetBeansProjects/TestProject Changing working directory... Current working directory: /Users/Wasi/NetBeansProjects/TestProject/test/ File is created at /Users/Wasi/NetBeansProjects/TestProject/test/test.txt 
+4
source

I am looking to find the working directory of a dynamically created process in Java,

You can, of course, find the working directory of the current Java process by looking at the value of the user.dir system property:

 String cwd = System.getProperty("user.dir"); 

But finding the working directory of another process is not possible unless you use special OS calls. On Linux, if you know pid, you can look at /proc/[pid]/cwd , but there is no simple equivalent in OSX or Windows that I know of.

This does not work, as soon as it ends, it exits with the same working directory.

Yes, you cannot issue a command to change the working directory, because as soon as cmd comes out, the working directory will be reset.

According to this page, you can set the working directory by assigning the user.dir system property:

 System.setProperty("user.dir", "/tmp"); 

However, this may be OS dependent and does not work in my OSX window. For example, the following code creates x1 and x2 files in the same directory:

 new File("x1").createNewFile(); // this doesn't seem to do anything System.setProperty("user.dir", "/tmp"); new File("x2").createNewFile(); 

This answer says there is no reliable way to do this in Java. I have always been of the opinion that you cannot change the working directory and that you have to be specific with new File(parent, filename) to show where the files are, etc.

+2
source

It cannot be achieved in Java using the ProcessBuilder directory() method, because it sets the working directory of the process, not where the binary is located. You have to do it on a different level.

If you work with GNU / Linux, whereis and update-alternative are your best bet. On Windows, you have where . Now we are talking about using commands in different operating systems and analyzing outputs. It can be tricky.

Some pseudo codes start with:

  • execute whereis plus command as parameter, ProcessBuilder
  • try to analyze the conclusion. You can handle multiple lines.

Or,

  • execute update-alternatives plus command as parameter, ProcessBuilder
  • try to analyze the conclusion. There may be several alternatives for one command, for example, for java , you can have different JDKs installed.
  • Or, list all the links in /var/libs/alternatives and find what you want, possibly with pipe. You can look here:

https://serverfault.com/questions/484896/is-there-a-way-to-list-all-configurable-alternatives-symlinks-for-similar-com

But I still doubt why you are doing this. So, if you can clarify the initial requirements, this will help a lot. This is to avoid the XY problem.

+2
source

What you can do is use the descriptor from sysinternals for windows

https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

or

ls -l / proc / [PID] / fd or pfiles [PID] for linux

and find the folder that was last used by this process.

 String commandToGetOpenFiles="handle... or ls..."; BufferedReader reader = new BufferedReader( new InputStreamReader(Runtime.getRuntime() .exec(commandToGetOpenFiles).getInputStream())); 

and to start the process and get the PID, use wmic process call create "cmd"

0
source

Use this to get the url of your current file directory:

 URL url = ClassLoader.getSystemResource(FileName); 

It works anywhere. Not only your computer, even in the cloud.

It returns a URL type (java.net). For ClassLoader you do not need to import anything.

In FileName, use any file name for which you want to get the path.

0
source

The question is a bit unclear, but if you are trying to find the current directory from the ININ of the current process, just do

 new File("").getAbsoluteFile().getAbsolutePath(); 
0
source

use the code below

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

Source: https://habr.com/ru/post/1015475/


All Articles