Maybe something like this will do:
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
public class GetBatchesDir {
public static class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
public Path pathFound=null;
Finder(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
boolean found(Path file) {
Path name = file.getFileName();
return (name != null && matcher.matches(name));
}
@Override
public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) {
if (found(dir)) {
pathFound=dir;
return TERMINATE;
}
else
return CONTINUE;
}
}
public static void main(String[] args) throws IOException {
Finder finder = new Finder("batches");
Files.walkFileTree(Paths.get("."), finder);
PrintWriter out;
if (finder.pathFound != null)
out=new PrintWriter(finder.pathFound.toString()+"/file.txt");
else {
new File("./batches").mkdir();
out=new PrintWriter("./batches/file.txt");
}
out.println("Hello");
out.close();
}
}
NIO is generally too ambitious for this but has neat finder functionality, so we use it for that, and simple File for the rest.
I have used "." as the root of the filesystem, you can probably find something more suitable. You wil also have to figure out what to do if the file exist, disk is full and so on.