Program Description:
I am writing a Java program which initial current directory is /home/user/Desktop. I want to run a bash command "du -s" in "location /home/user/project/" for finding the size of that folder so that I can to use the size of the folder in my project. I cannot post the entire code as it is having some sensitive data. I am just posting the code which is needed.
Here is what I have done:-
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.File;
public class Exec_in_cur_dir {
public static void main(String[] args) {
try {
StringBuffer output = new StringBuffer();
String Command ="cd /home/user/project"; //Bash Command
// create a process and execute
Process p = Runtime.getRuntime().exec(Command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println(output.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
So if I execute the program, the output is
Cannot run program "cd": error=2.
But it is working every other commands like
ls
df -h
- etc.
My Question:
From the above analysis what I have inferred is my java program cannot be able to change directory. So how can I change the directory path and execute a bash command.