How to check if a file and executable exists with Java, in Unix?

I am trying to check if a file exists on Unix from a Java process.

I'm struggling with Runtime.getRuntime().exec()

The command I am trying to run, test -x $VAR/path/to/file

notice the Unix variable inside the path.

The command returns 0 or 1, but I don't know how to get an indication of this from within Java.

I am currently doing the following:

String cmd = "test -x $VAR/filename";
Process proc = Runtime.getRuntime().exec(cmd);
int exitCode = proc.waitFor();

      

I can also add ;echo $?

to the command that will print the value 0/1, but I don't know how to get the command output.

+3


source to share


2 answers


You can use Java.io.File class It has methods canExecute()

andexists()

Example:



//Create new File
File file = new File("C:/test/testFile.exe");
//Check if file exists
if(file.exists()==true){
System.out.println("The File Exists");
//Check if file is executable
if(file.canExecute()==true){
System.out.println("The File is executable");

}

}

      

+2


source


I think what you are looking for is File#exists()

also File#canExecute()

to check for its existence and check if it is executable



+3


source







All Articles