Java I/O (Input and Output) is used to process the input and produce the output. Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations. Handling files is also done in java by Java I/O API.
These examples assume that you already know what Java 7's NIO is in general, and you are used to writing code using java.io.File. Use these examples as a means to quickly find more NIO-centric documentation for migrating.
There is much more to Java 7's NIO such as memory-mapped files or opening a ZIP or JAR file using FileSystem. These examples will only cover a limited number of basic use cases..
As a basic rule, if you are used to perform a file system read/write operation using a java.io.File instance method, you will find it as a static method within java.nio.file.Files.
Point to a path
// -> IO File file = new File("io.txt"); // -> NIO Path path = Paths.get("nio.txt");
Paths relative to another path
// Forward slashes can be used in place of backslashes even on a Windows operating system // -> IO File folder = new File("C:/"); File fileInFolder = new File(folder, "io.txt"); // -> NIO Path directory = Paths.get("C:/"); Path pathInDirectory = directory.resolve("nio.txt");
Converting File from/to Path for use with libraries
// -> IO to NIO Path pathFromFile = new File("io.txt").toPath(); // -> NIO to IO File fileFromPath = Paths.get("nio.txt").toFile();
Check if the file exists and delete it if it does
// -> IO if (file.exists()) { boolean deleted = file.delete(); if (!deleted) { throw new IOException("Unable to delete file"); } } // -> NIO Files.deleteIfExists(path);
Write to a file via an OutputStream
There are several ways to write and read from a file using NIO for different performance and memory constraints, readability and use cases, such as FileChannel, Files.write(Path path, byte\[\] bytes, OpenOption... GoalKicker.com – Java® Notes for Professionals 451 options)... In this example, only OutputStream is covered, but you are strongly encouraged to learn about memory-mapped files and the various static methods available in java.nio.file.Files.
List<String> lines = Arrays.asList( String.valueOf(Calendar.getInstance().getTimeInMillis()), "line one", "line two"); // -> IO if (file.exists()) { // Note: Not atomic throw new IOException("File already exists"); } try (FileOutputStream outputStream = new FileOutputStream(file)) { for (String line : lines) { outputStream.write((line + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); } } // -> NIO try (OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW)) { for (String line : lines) { outputStream.write((line + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); } }
Iterating on each file within a folder
// -> IO for (File selectedFile : folder.listFiles()) { // Note: Depending on the number of files in the directory folder.listFiles() may take a long time to return System.out.println((selectedFile.isDirectory() ? "d" : "f") + " " + selectedFile.getAbsolutePath()); } // -> NIO Files.walkFileTree(directory, EnumSet.noneOf(FileVisitOption.class), 1, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path selectedPath, BasicFileAttributes attrs) throws IOException { System.out.println("d " + selectedPath.toAbsolutePath()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path selectedPath, BasicFileAttributes attrs) throws IOException { System.out.println("f " + selectedPath.toAbsolutePath()); return FileVisitResult.CONTINUE; } });
Recursive folder iteration
// -> IO recurseFolder(folder); // -> NIO // Note: Symbolic links are NOT followed unless explicitly passed as an argument to Files.walkFileTree Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { System.out.println("d " + selectedPath.toAbsolutePath()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path selectedPath, BasicFileAttributes attrs) throws IOException { System.out.println("f " + selectedPath.toAbsolutePath()); return FileVisitResult.CONTINUE; } }); private static void recurseFolder(File folder) { for (File selectedFile : folder.listFiles()) { System.out.println((selectedFile.isDirectory() ? "d" : "f") + " " + selectedFile.getAbsolutePath()); if (selectedFile.isDirectory()) { // Note: Symbolic links are followed recurseFolder(selectedFile); } } }
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions