Cnf271 Cnf271 - 1 month ago 5
Java Question

How to escape java special characters and run Linux commands

I'm writing a java program to find specific files(files with special permissions and by file type) within the directory. The following command executes properly since there aren't any special characters.

find /home/Cnf271/Desktop/ -perm -4000 ;


Now if i try to execute the following command using my java program, terminal doesn't give a proper result.

find /home/Cnf271/Desktop/ -name "*.txt" -perm -4000 -exec ls -ldb {} \;


Java Program,

//
..
System.out.print("Please enter directory path: ");
fileDirectory = scan.next();

System.out.print("Please enter file type (txt/pdf): ");
fileType = scan.next();
filetypecmd = " \"*." +fileType+ "\" ";

System.out.println(filetypecmd);
String cmd = "find "+fileDirectory+ " -name "+filetypecmd+" -perm -4000" ;

Runtime run = Runtime.getRuntime();

Process process = run.exec(cmd);

BufferedReader buffer = new BufferedReader(new InputStreamReader(process.getInputStream()));

String space = "";

while ((space=buffer.readLine())!=null) {

System.out.println(space);
..
//


Program works fine.however,
String cmd
command doesn't give me a proper result because linux command is wrapped with special characters.How do I execute the following command in my java program.

find /home/Cnf271/Desktop/ -name "*.txt" -perm -4000 -exec ls -ldb {} \;


Thanks.

Answer

Elements that need to be quoted (or escaped special characters) for a Linux command shell do not need to be quoted when being executed by Runtime.exec() (they do not need to be protected from the shell).

In your code, remove the extra quotes on the wildcard search parameters:

String filetypecmd = " *." + fileType + " ";

I tested this and was able to run your code correctly on Linux, but I had to remove your -perm -4000 parameters to get results in my case. I received no results with the extra quotes around "*.txt" but all was well without them.

By the way, you can also use a Scanner to collect the results:

Scanner results = new Scanner(process.getInputStream());
while (results.hasNextLine())
{
    System.out.println(results.nextLine());
}