Change directory in Java like Perl chdir

238 Views Asked by At

In my company we are updating web software that uses a Perl script to perform specific operations. In updating the script, it will be rewritten in Java.

The main operations of the script are to move between folders and copy / remove files within them.

I need to perform Java commands like chdir, rcopy, rmove, fcopy, etc which are used in the current Perl script. Searching both on the web and here on Stack Overflow I read that Java does not offer equivalent commands. Is there a way to perform these operations?

For now from the Java documentation I was thinking of using java.nio.file.Files. Are there better alternatives?

2

There are 2 best solutions below

1
pedrohreis On

If you can use absolute paths (you can convert a relative path to an absolute path by means of getAbsolutePath), it should be as simple as:

Path source = Paths.get("/my/source/dir/sourcefile.txt");
Path target = Paths.get("/my/target/dir/targetfile.txt"); 

Files.move(source, target); // move
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); //copy
3
Vladmix6 On

I'm not sure if you can execute all of those commands in Java (because I'm not familiar with all of them), but at least for the usual System commands (like "chdir") should be possible using this approach:

Process exec = Runtime.getRuntime().exec("sudo -v");

or:

Process exec = Runtime.getRuntime().exec("pkill -f " + processName);

or like this:

String[] cmd = { "/bin/sh", "-c", "cd /var; ls -l" };
Process p = Runtime.getRuntime().exec(cmd);

As you can see "exec" method requires a string containing your desired console command. Also for more complex explanations you can consult this book: https://alvinalexander.com/java/edu/pj/pj010016/. I hope I gor it right ( your question I mean). Cheers!