java8 : Files/path/paths 、Files.write + Files.readAllLines/Files.readAllBytes、Files.newBufferedWrite

读、写、创建文件

打印信息

private static void info() throws IOException {
    
    
    //返回以相对地址为基础的路径,不判断文件是否存在
    Path path = Paths.get("src\\com\\xq\\demo\\java8\\Test1.java").toAbsolutePath();
    System.out.println(path);
    System.out.println("文件是否存在: " + Files.exists(path));
    System.out.println("是否是目录: " + Files.isDirectory(path));
    System.out.println("是否是可执行文件: " + Files.isExecutable(path));
    System.out.println("是否可读: " + Files.isReadable(path));
    System.out.println("判断是否是一个文件: " + Files.isRegularFile(path));
    System.out.println("是否可写: " + Files.isWritable(path));
    System.out.println("文件是否不存在: " + Files.notExists(path));
    System.out.println("文件是否隐藏: " + Files.isHidden(path));
    System.out.println("文件大小: " + Files.size(path));
    System.out.println("文件存储在SSD还是HDD: " + Files.getFileStore(path));
    System.out.println("文件修改时间:" + Files.getLastModifiedTime(path));
    System.out.println("文件拥有者: " + Files.getOwner(path));
    System.out.println("文件类型: " + Files.probeContentType(path));
    System.out.println("获取文件名: " + path.getFileName());
    System.out.println("获取父目录: " + path.getParent());
    System.out.println("获取根目录: " + path.getRoot());
}

Files.write + Files.readAllLines/Files.readAllBytes : 简单读写

private static void readWriteFile() throws IOException {
    
    
    /*================写入======================*/
    Path path = Paths.get("0.txt");

    String content = String.valueOf(System.currentTimeMillis());
    System.out.println("write=" + content);
    Files.write(path, content.getBytes(StandardCharsets.UTF_8));

    content = "-"+ Integer.MAX_VALUE;
    System.out.println("write append=" + content);
    //向指定文件追加内容
    Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);

    /*================读取======================*/
    //按行读取
    Stream<String> stringStream = Files.lines(path, StandardCharsets.UTF_8);
    stringStream.forEach(System.out::println);

    //按行读取
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    for (int i = 0; i < lines.size(); i++) {
    
    
        System.out.println("[" + i + "]" + lines.get(i));
    }

    //整个文件一起读取
    byte[] allBytes = Files.readAllBytes(path);
    System.out.println(new String(allBytes, StandardCharsets.UTF_8));
}

Files.newBufferedWriter + Files.newBufferedReader : 缓冲区读写


/**
 * Files.newBufferedWriter +  Files.newBufferedReader
 * BufferedReader(缓冲区读取内容,避免中文乱码)
 * 访问文件系统的所有方法都可以抛出 IOException。
 * 最好的做法是通过 JDK7 引入的 try-with-resources 语句来捕获这些异常。
 * 使用 try-with-resources 语句,编译器会自动生成关闭的代码。帮你自动释放资源。
 */
private static void writeFile1() {
    
    
    String s = LocalTime.now().toString();
    System.out.println("write=" + s);
    Path path = Paths.get("1.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
    
    
        writer.write(s, 0, s.length());
    } catch (IOException x) {
    
    
        System.err.format("IOException: %s%n", x);
    }

    try (BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    
    
        String line;
        while ((line = bufferedReader.readLine()) != null) {
    
    
            System.out.println("read=" + line);
        }
    } catch (IOException e) {
    
    
        System.err.format("IOException: %s%n", e);
    }
}

/**
 * Files.newBufferedWriter +  Files.newBufferedReader
 * BufferedReader(缓冲区读取内容,避免中文乱码)
 * 将文件 I / O 方法嵌入到 try 块中,然后捕获块中的任何异常 catch。
 * 如果你的代码打开了任何流或通道, 你应该在一个 finally 块中关闭它们。
 */
private static void writeFile2() {
    
    
    String s = LocalDate.now().toString();
    System.out.println("write=" + s);
    Path path = Paths.get("2.txt");
    BufferedWriter writer = null;
    try {
    
    
        writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
        writer.write(s, 0, s.length());
    } catch (IOException x) {
    
    
        System.err.format("IOException: %s%n", x);
    } finally {
    
    
        try {
    
    
            if (writer != null) {
    
    
                writer.close();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    try {
    
    
        BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
    
    
            System.out.println("read=" + line);
        }
        bufferedReader.close();
    } catch (IOException e) {
    
    
        System.err.format("IOException: %s%n", e);
    }
}

Files.newOutputStream + Files.newInputStream : 输入输出流


/**
 * Files.newOutputStream + Files.newInputStream
 */
private static void writeFile3() {
    
    
    String s = LocalDateTime.now().toString();
    System.out.println("write=" + s);
    Path path = Paths.get("3.txt");
    try (OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))) {
    
    
        writer.write(s);
    } catch (IOException x) {
    
    
        System.err.format("IOException: %s%n", x);
    }

    try (InputStream inputStream = Files.newInputStream(path, StandardOpenOption.READ);
         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
    
    
        String line;
        while ((line = reader.readLine()) != null) {
    
    
            System.out.println("read=" + line);
        }
    } catch (Exception e) {
    
    
        System.err.format("IOException: %s%n", e);
    }
}

demo

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Stream;

public class Test2 {
    
    

    public static void main(String[] args) throws IOException {
    
    
        info();

        readWriteFile();

        writeFile1();
        System.out.println("====================1=====================");
        writeFile2();
        System.out.println("====================2=====================");
        writeFile3();
        System.out.println("====================3=====================");

    }

    /**
     * Files.newBufferedWriter +  Files.newBufferedReader
     * BufferedReader(缓冲区读取内容,避免中文乱码)
     * 访问文件系统的所有方法都可以抛出 IOException。
     * 最好的做法是通过 JDK7 引入的 try-with-resources 语句来捕获这些异常。
     * 使用 try-with-resources 语句,编译器会自动生成关闭的代码。帮你自动释放资源。
     */
    private static void writeFile1() {
    
    
        String s = LocalTime.now().toString();
        System.out.println("write=" + s);
        Path path = Paths.get("1.txt");
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
    
    
            writer.write(s, 0, s.length());
        } catch (IOException x) {
    
    
            System.err.format("IOException: %s%n", x);
        }

        try (BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    
    
            String line;
            while ((line = bufferedReader.readLine()) != null) {
    
    
                System.out.println("read=" + line);
            }
        } catch (IOException e) {
    
    
            System.err.format("IOException: %s%n", e);
        }
    }

    /**
     * Files.newBufferedWriter +  Files.newBufferedReader
     * BufferedReader(缓冲区读取内容,避免中文乱码)
     * 将文件 I / O 方法嵌入到 try 块中,然后捕获块中的任何异常 catch。
     * 如果你的代码打开了任何流或通道, 你应该在一个 finally 块中关闭它们。
     */
    private static void writeFile2() {
    
    
        String s = LocalDate.now().toString();
        System.out.println("write=" + s);
        Path path = Paths.get("2.txt");
        BufferedWriter writer = null;
        try {
    
    
            writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
            writer.write(s, 0, s.length());
        } catch (IOException x) {
    
    
            System.err.format("IOException: %s%n", x);
        } finally {
    
    
            try {
    
    
                if (writer != null) {
    
    
                    writer.close();
                }
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }

        try {
    
    
            BufferedReader bufferedReader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
    
    
                System.out.println("read=" + line);
            }
            bufferedReader.close();
        } catch (IOException e) {
    
    
            System.err.format("IOException: %s%n", e);
        }
    }


    /**
     * Files.newOutputStream + Files.newInputStream
     */
    private static void writeFile3() {
    
    
        String s = LocalDateTime.now().toString();
        System.out.println("write=" + s);
        Path path = Paths.get("3.txt");
        try (OutputStream outputStream = Files.newOutputStream(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))) {
    
    
            writer.write(s);
        } catch (IOException x) {
    
    
            System.err.format("IOException: %s%n", x);
        }

        try (InputStream inputStream = Files.newInputStream(path, StandardOpenOption.READ);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
    
    
            String line;
            while ((line = reader.readLine()) != null) {
    
    
                System.out.println("read=" + line);
            }
        } catch (Exception e) {
    
    
            System.err.format("IOException: %s%n", e);
        }
    }

    private static void readWriteFile() throws IOException {
    
    
        /*================写入======================*/
        Path path = Paths.get("0.txt");

        String content = String.valueOf(System.currentTimeMillis());
        System.out.println("write=" + content);
        Files.write(path, content.getBytes(StandardCharsets.UTF_8));

        content = "-"+ Integer.MAX_VALUE;
        System.out.println("write append=" + content);
        //向指定文件追加内容
        Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);

        /*================读取======================*/
        //按行读取
        Stream<String> stringStream = Files.lines(path, StandardCharsets.UTF_8);
        stringStream.forEach(System.out::println);

        //按行读取
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        for (int i = 0; i < lines.size(); i++) {
    
    
            System.out.println("[" + i + "]" + lines.get(i));
        }

        //整个文件一起读取
        byte[] allBytes = Files.readAllBytes(path);
        System.out.println(new String(allBytes, StandardCharsets.UTF_8));
    }

    private static void info() throws IOException {
    
    
        //返回以相对地址为基础的路径,不判断文件是否存在
        Path path = Paths.get("src\\com\\xq\\demo\\java8\\Test1.java").toAbsolutePath();
        System.out.println(path);
        System.out.println("文件是否存在: " + Files.exists(path));
        System.out.println("是否是目录: " + Files.isDirectory(path));
        System.out.println("是否是可执行文件: " + Files.isExecutable(path));
        System.out.println("是否可读: " + Files.isReadable(path));
        System.out.println("判断是否是一个文件: " + Files.isRegularFile(path));
        System.out.println("是否可写: " + Files.isWritable(path));
        System.out.println("文件是否不存在: " + Files.notExists(path));
        System.out.println("文件是否隐藏: " + Files.isHidden(path));
        System.out.println("文件大小: " + Files.size(path));
        System.out.println("文件存储在SSD还是HDD: " + Files.getFileStore(path));
        System.out.println("文件修改时间:" + Files.getLastModifiedTime(path));
        System.out.println("文件拥有者: " + Files.getOwner(path));
        System.out.println("文件类型: " + Files.probeContentType(path));
        System.out.println("获取文件名: " + path.getFileName());
        System.out.println("获取父目录: " + path.getParent());
        System.out.println("获取根目录: " + path.getRoot());
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_31057219/article/details/132475224
今日推荐