The new file operation class Files in java7

jdk7 provides a new file operation class. Under the java.nio.file package, it also provides the paths class. I tried it out and it's still good. Let me share the code with you:

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FilesTest {
    public static void main(String[] args) throws Exception {
        //If test does not exist, create the directory
        if(Files.notExists(Paths.get("E:\\test"))){
            Files.createDirectories(Paths.get("E:\\test"));
        }

        if(Files.notExists(Paths.get("E:\\test\\a.txt"))){
            //Create a.txt file
            Files.createFile(Paths.get("E:\\test\\a.txt"));
        }

        //Return to bufferWriter to write files directly, using the try-with-source writing method, the connection will be automatically closed
        //StandardCharsets.UTF_8 encoding of utf-8
        try(BufferedWriter bw = Files.newBufferedWriter(Paths.get("E:\\test\\a.txt"), StandardCharsets.UTF_8)){
            bw.write("dksdkfkdks sdkfjksdjl ddd dksk dsdfsdf sdfsldfjewofsl dsdfsdfsdfesdf\n"
                    + "sdfs daaaaaaaaaa dfesdfkajfoafmoapfhq sladjfowqmfoqhf ddsdfsf");
            bw.flush();
        }

        //Create b.txt file
        Files.createFile(Paths.get("E:\\test\\b.txt"));
        //The way to return the stream, the above example returns BufferedWriter, the parameter StandardOpenOption.APPEND is not passed, it is overwritten
        try(OutputStream os = Files.newOutputStream(Paths.get("E:\\test\\b.txt"),
                StandardOpenOption.APPEND)){
            os.write(("ddddd".getBytes()));
            os.close();
        }

        Files.deleteIfExists(Paths.get("E:\\test\\b.txt"));
        if(Files.exists(Paths.get("E:\\test\\a.txt"))){
            //Can be used to modify the name, similar to linux's mv
            Files.move(Paths.get("E:\\test\\a.txt") ,Paths.get("E:\\test\\c.txt"));
            // move the file
            Files.move(Paths.get("E:\\test\\c.txt") ,Paths.get("D:\\c.txt"));
        }

    }
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326567867&siteId=291194637