If you have the directory name in myDirectoryPath,
import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}
Answer from Mike Samuel on Stack OverflowIf you have the directory name in myDirectoryPath,
import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}
I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles method and you can process each file.
You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi
Here's an example:
Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
while(it.hasNext()){
System.out.println(((File) it.next()).getName());
}
You can change null and put a list of extentions if you wanna filter. Example: {".xml",".java"}
java - Process files in directories and sub-directories concurrently - Stack Overflow
java - Process incoming files in a directory - Stack Overflow
Hot to set the working directory of a process in Java - Stack Overflow
java - execute file from defined directory with Runtime.getRuntime().exec - Stack Overflow
Check for new files, process them, rinse, and repeat:
while (true) {
File[] files = new File(DIRECTORY_PATH).listFiles();
for (File file : files) {
/* do something with this file */
//and delete it when finished
file.delete();
}
//Pause for a second before checking again
Thread.sleep(1000);
}
JDK 7 includes the java.nio.file.WatchService class that allows you to be notified of filesystem changes when they happen rather than continuously poll. It is currently available in OpenJDK as well:
JDK 7 features
OpenJDK WatchService tutorial
It should be possible to call the executable with a specific working directory using Runtime.exec(String command, String[] envp, File dir)
as follows:
Process process2=Runtime.getRuntime().exec("/data/data/my-package/files/myfile",
null, new File("/data/data/my-package/files"));
maybe without the full path to myfile
Process process2=Runtime.getRuntime().exec("myfile",
null, new File("/data/data/my-package/files"));
Context#getFilesDir() instead of hardcoding the path should work too and is safer / cleaner than specifying the path yourself since it is not guaranteed that /data/data/..
is always the correct path for all devices.
Process process2=Runtime.getRuntime().exec("myfile",
null, getFilesDir()));
The problem with cd somewhere is that the directory is changed for a different Process so the second call to exec in a new Process does not see the change.
It works for me when I use the following overloaded method:
public Process exec(String command, String[] envp, File dir)
For example:
File dir = new File("C:/Users/username/Desktop/Sample");
String cmd = "java -jar BatchSample.jar";
Process process = Runtime.getRuntime().exec(cmd, null, dir);
The command just stores the command you want to run in command line. dir just stores the path of your .jar file to be executed.
Are you looking for something like this?
System.out.println("Current working directory: " + System.getProperty("user.dir"));
System.out.println("Changing working directory...");
// changing the current working directory
System.setProperty("user.dir", System.getProperty("user.dir") + "/test/");
// print the new working directory path
System.out.println("Current working directory: " + System.getProperty("user.dir"));
// create a new file in the current working directory
File file = new File(System.getProperty("user.dir"), "test.txt");
if (file.createNewFile()) {
System.out.println("File is created at " + file.getCanonicalPath());
} else {
System.out.println("File already exists.");
}
It outputs:
Current working directory: /Users/Wasi/NetBeansProjects/TestProject
Changing working directory...
Current working directory: /Users/Wasi/NetBeansProjects/TestProject/test/
File is created at /Users/Wasi/NetBeansProjects/TestProject/test/test.txt
I am looking to find the working directory of a dynamically created process in Java,
You can certainly lookup the working directory of the current Java process by looking at the value of the user.dir system property:
String cwd = System.getProperty("user.dir");
But finding out the working directory of another process is not possible unless you are using special OS calls. On Linux, if you know the pid then you can look at /proc/[pid]/cwd but there is no easy equivalent in OSX or Windows that I know about.
This does not work, once it finishes it comes out with the same working directory.
Yeah, you are not able to issue a command to change the working directory because once the cmd exits, the working directory will be reset.
According to this page, you can set the working directory by assigning the user.dir system property:
System.setProperty("user.dir", "/tmp");
However this may be OS dependent and doesn't work on my OSX box. For example, the following code creates the x1 and x2 files in the same directory:
new File("x1").createNewFile();
// this doesn't seem to do anything
System.setProperty("user.dir", "/tmp");
new File("x2").createNewFile();
This answer says that there is no reliable way to do this in Java. I've always taken the opinion that you can't change the working directory and that you should be specific with new File(parent, filename) to show where files live, etc..
As Jarrod Roberson states in his answer here:
One way would be to use the system property
System.getProperty("user.dir");this will give you "The current working directory when the properties were initialized". This is probably what you want. to find out where thejavacommand was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn't that useful in most cases.The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.
public class Test { public static void main(final String[] args) { final String dir = System.getProperty("user.dir"); System.out.println("current dir = " + dir); } }if you are in
/User/me/and your .jar file containing the above code is in/opt/some/nested/dir/the commandjava -jar /opt/some/nested/dir/test.jar Testwill outputcurrent dir = /User/me.You should also as a bonus look at using a good object oriented command line argument parser. I highly recommend JSAP, the Java Simple Argument Parser. This would let you use
System.getProperty("user.dir")and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back onuser.dirif nothing was passed in.
Example : GetExecutionPath
import java.util.*;
import java.lang.*;
public class GetExecutionPath
{
public static void main(String args[]) {
try{
String executionPath = System.getProperty("user.dir");
System.out.print("Executing at =>"+executionPath.replace("\\", "/"));
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
}
output for the above will be like
C:\javaexamples>javac GetExecutionPath.jav
C:\javaexamples>java GetExecutionPath
Executing at =>C:/javaexamples
You can do some crazy stuff:
String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
absolute = absolute.substring(0, absolute.length() - 1);
absolute = absolute.substring(0, absolute.lastIndexOf("/") + 1);
String configPath = absolute + "config/file.properties";
String os = System.getProperty("os.name");
if (os.indexOf("Windows") != -1) {
configPath = configPath.replace("/", "\\\\");
if (configPath.indexOf("file:\\\\") != -1) {
configPath = configPath.replace("file:\\\\", "");
}
} else if (configPath.indexOf("file:") != -1) {
configPath = configPath.replace("file:", "");
}
I use this to read out a config file relativ to execution path. You can use it also to get execution path of your jar file.
To implement this you can use the ProcessBuilder class, here's how it would look like:
File pathToExecutable = new File( "resources/external.exe" );
ProcessBuilder builder = new ProcessBuilder( pathToExecutable.getAbsolutePath(), "-i", "input", "-o", "output");
builder.directory( new File( "resources" ).getAbsoluteFile() ); // this is where you set the root folder for the executable to run with
builder.redirectErrorStream(true);
Process process = builder.start();
Scanner s = new Scanner(process.getInputStream());
StringBuilder text = new StringBuilder();
while (s.hasNextLine()) {
text.append(s.nextLine());
text.append("\n");
}
s.close();
int result = process.waitFor();
System.out.printf( "Process exited with result %d and output %s%n", result, text );
It's quite a bunch of code, but gives you even more control on how the process is going to be run.
Use this form of the exec method to specify a working directory
public Process exec(String[] cmdarray,
String[] envp,
File dir)
throws IOException
The working directory is the third argument. You can pass null for envp if you don't need to set any special environment.
There's also this convenience method:
public Process exec(String command,
String[] envp,
File dir)
throws IOException
...where you specify the command in one string (it just gets turned into an array for you; see the docs for details).