Below program throws "java.nio.file.NoSuchFileException" when subdirecties doesnot exist in path. Could some one please help how can I acheive this ? I want to insert records in asyncronous way.
public static void main(String[] args) {
String str = "testing application2.";
Path path = Paths.get("/Users/santosh/test/operatord/testsd.txt");
Set<StandardOpenOption> set = new HashSet<>();
set.add(WRITE);
set.add(CREATE);
try {
AsynchronousFileChannel asyncfileChannel = AsynchronousFileChannel.open(path, set,
Executors.newFixedThreadPool(10));
TestCompletionHandler handler = new TestCompletionHandler();
ByteBuffer dataBuffer = ByteBuffer.wrap(str.getBytes());
Attachment attachment = new Attachment(asyncfileChannel);
asyncfileChannel.write(dataBuffer, 0, attachment, handler);
attachment.getResponse().join();
System.out.println(new String(Files.readAllBytes(path)));
} catch (Throwable e) {
e.printStackTrace();
}
}
That is correct. Opening a file won't create the directories on the path to the file. You will also get this behavior with all of the standard APIs for opening a file.
You need to create the missing directories as a separate operation.
The preferred way to do this is to use
Files.makeDirectories
method; see javadoc. This will attempt to create all of the missing directories.You could also use the legacy
File.mkdirs(path)
method; see javadoc. It does the same thing, but it has the disadvantage that it doesn't report any meaningful diagnostics if the directory (or directories) cannot be created.