[Java] Rewrite the functions created by myself in the past from java.io.File with NIO.2.

background

If you want to manipulate files and directories in Java, the following classes are generally taken care of.

The File class has been around for a long time. NIO.2 is a class introduced in Java 7 and is newer than the File class.

So, if you want to implement it newly, you want to use NIO.2.

This time, I will introduce the code that I wrote in java.io.File and rewritten in NIO.2.

Functions to introduce

--Does the file exist in the specified directory? --Delete all specified directories including their contents

Does the file exist in the specified directory?

java 6 or earlier

import java.io.File;

public class Demo {
    public static void main(String[] args) {
        File file = new File("C:/temp/");

        //Get a list of file names and check for existence
        if (file.listFiles().length == 0) {
            System.out.println("There are no files.");
        } else {
            System.out.println("There is a file.");
        }
    }
}

The return value of File.listFiles () is returned as an array of type File. It is a flow to judge by looking at the length of the array with that lengh.

java 7 or later

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Demo {
    public static void main(String[] args) {
        Path path = Paths.get("C:/temp/");

        try {
            if (Files.list(path).findAny().isPresent()) {
                System.out.println("There is a file.");
            } else {
                System.out.println("There are no files.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files.list gets the entries in the directory and returns them in Strem.


```findany()```Returns the first element found optionally.
```ispresent()```Returns false if optional holds a null value, true if it is not null.

# Delete all the specified directories including the contents

## java 6 or earlier

```java
import java.io.File;

public class Demo {
    public static void main(String[] args) {
        File dir = new File("C:/temp/");
        deleteDir(dir);
    }

    public static void deleteDir(File dir) {
        if (dir.exists() && dir.isDirectory()) {
            for (File child : dir.listFiles()) {
                if (child.isDirectory()) {
                    deleteDir(child);
                } else {
                    child.delete();
                }
            }
        }
        dir.delete();
    }
}

java 8 or later

**Caution! ** Since I am using Stream, it only works with java8 or later.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;

public class Demo {
    public static void main(String[] args) {
        Path path = Paths.get("C:/temp/");

        //Delete all directories
        try {
            Files.walk(path).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
            path.toFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files.walk(path)So, IOException may occur, so please throw or catch.



#### **`Files.walk(path)Is getting a list containing subdirectories.`**
```walk(path)Is getting a list containing subdirectories.


#### **`sorted(Comparator.reverseOrder())Sorts in descending order.`**
```reverseOrder())Sorts in descending order.

 This will bring the files to the top and sort the directories to the back.
 Then, the Paths type extracted by filtering is converted to the Files type and deleted in a loop.
 (I'm sorry. I may not be able to explain it well.)

 You can convert ``` Stream <Path>` `` to ``` List <Path>` `` by doing the following.

#### **`.collect(Collectors.toList())Just add ...`**
List<Path> list = Files.walk(path).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
for (Path p : list) {
    System.out.println(p);
}

bonus

It's a feature that happened to come after trial and error. I will introduce it because it is a great deal.

Delete files in the specified directory

java 8 or later

**Caution! ** Since I am using Stream, it only works with java8 or later.

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Demo {
    public static void main(String[] args) {
        Path path = Paths.get("C:/temp/");

        //Delete files in the directory(Do not delete subdirectories)
        try {
            Files.walk(path).filter(Files::isRegularFile).map(Path::toFile).forEach(File::delete);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

.filter(Files::isRegularFile)So, I'm checking if it's a normal file.


 This will exclude the directory from deletion.

# Finally

 I'm still new to Java 8 lambda expressions, Streams, Optional, etc.
 The feeling of being outdated is amazing, so I want to do something about it. But the more I look up, the less I understand and I'm addicted to the swamp ...


Recommended Posts

[Java] Rewrite the functions created by myself in the past from java.io.File with NIO.2.
[Java] Set the time from the browser with jsoup
Text extraction in Java from PDF with pdfbox-2.0.8
[Java] Judgment by entering characters in the terminal
How to call functions in bulk with Java reflection
Read the packet capture obtained by tcpdump in Java
Rewrite the code for java.io.File with java.nio.Path and java.nio.Files
I dealt with Azure Functions not working in Java
[Java] Get the file path in the folder with List
Azure functions in java
Find the address class and address type from the IP address with Java
JSON in Java and Jackson Part 1 Return JSON from the server
Correct the character code in Java and read from the URL
Think about the differences between functions and methods (in Java)