Files API in JAVA 8

Java8 comes with a great Files API. Doing anything with folders and files are much easier than ever. You don’t have to use the File object packed with java.io package. Let’s take a look at that Files API in JAVA 8 with some examples.

Creating a File with Files API in JAVA 8

Files API has a static method called createFile. You just pass a Paths object with the filename in it.

Files.createFile(Paths.get("demoFile.txt"));

Get File’s AbsolutePath

You can use Paths object to get the absolute path of a file.

Paths.get("create.csv").toAbsolutePath();

Check File Exist or Not

boolean exist = Files.exists(Paths.get("demoFile.txt"));
System.out.println("Result is "+exist);

Create Directory

You can use Files API to create a folder by using the static createDirectory method.

Path path = Files.createDirectory(Paths.get("DemoFolder"));

Then you can create a File under it.

Path path = Files.createDirectory(Paths.get("Demo"));
Files.createFile(Paths.get(path.toAbsolutePath()+"/demoFile.txt"));

Delete Directory or File

Files.delete(Paths.get("DemoFolder"));
Files.delete(Paths.get("DemoFolder/file.txt"));

Write to a File

We create a DemoFolder and then create a text file. Then append some text inside of it.

Path source = Files.createDirectory(Paths.get("DemoFolder"));
Path filePath = Files.createFile(Paths.get(source.toAbsolutePath()+"/original.txt"));
Files.write(filePath,"DEMOTEXT".getBytes("UTF-8"), StandardOpenOption.APPEND);

Copy File to Another Folder

Path sourcePath      = Paths.get("data/source.txt");
Path destinationPath = Paths.get("data/destination.txt");
Files.copy(sourcePath, destinationPath,
            StandardCopyOption.REPLACE_EXISTING);

Get Line Count of File

Path rootPath = Paths.get("Source/original.txt");
long lineCount = Files.lines(rootPath).count();
System.out.println("Line count is "+lineCount);

Those commands are mostly the basic stuff that you would need in any project. But there is advanced stuff to explore in the new Files API in JAVA 8. Here is some of them.

Search for a File under a Directory

This is a tricky operation as there might be parent-child relation between folders and you need to look every folder to find your file. For this operation, you need to implement walkFileTree. This method will look over all the folders under the rootPath that you provide. You need to provide a signal to terminate the search operation in case the file is found. There are many signals that you can send like CONTINUE, SKIP_SUBTREE etc…

Path rootPath = Paths.get("SourceFolder");
     String fileToFind = "findme.txt";

      try {
            Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    String fileString = file.toAbsolutePath().toString();
                    if(fileString.contains(fileToFind)){
                        System.out.println("file found at path: " + file.toAbsolutePath());
                        return FileVisitResult.TERMINATE;
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch(IOException e){
            e.printStackTrace();
        }
}

In this operation, the search will start from the directory located under SourceFolder. Files will be matches the file name that we search for. In case it’s not a match, we send a CONTINUE signal, in case the file is found we send the TERMINATE signal.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.