Changing the current directory

Question:
How does one change the current working directory of a Java program or a java.lang.Process? The equivalent of the Unix chdir system call seems to be absent.

Answer:
There is no way to change the current working directory of a Java program. If your application needs to keep track of directories, you should start off by using System.getProperty(“user.dir”) to get the current working directory. Store this in a variable that tracks the current directory, and, as you change the notion of current directory in your program, update the variable. This is usually necessary for Java programs that look for files in relative directories and need to construct absolute paths.

Sometimes Java programs need to spawn other programs using Runtime.exec, but the programs require a different working directory than the current one used by the Java program. To change the initial directory of an execed program, you have to depend on the system shell for your platform (if you have one). For Unix, just calling something like runtime.exec(“cd ” + newDirectory + “; ” + commandName) will do what you need. An alternative is just to write a simple script that sets up the environment for the command and call the script from your Java program.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS