Java IO五种创建写入文件的方法

Java IO之5种创建写入文件的方法

Files.new BufferedWriter(Java 8)
Files.writer(Java 7推荐)
PrintWriter
File.createNewFile
FileOutputStream.writer(byte[] b)管道流

Files.new BufferedWriter

public class testCreateFile1 {
    @Test
    public void test1() throws IOException {
        String fileName = "C:\\Users\\DELL\\Desktop\\test\\ceshi.txt";
        Path path = Paths.get(fileName);
        //使用newBufferedWriter创建文件并写文件
        //使用try-with-resource方法关闭流,不用手动关闭
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
            writer.write("第二次使用Files.newBufferedWriter创建文件!!!");
        }

        //追加写模式
        try(BufferedWriter writer = Files.newBufferedWriter(path,StandardCharsets.UTF_8, StandardOpenOption.APPEND)){
            writer.write("使用这种【BufferedWriter writer = Files.newBufferedWriter(path,StandardCharsets.UTF_8, StandardOpenOption.APPEND)】追加模式");
        }
    }
}

Files.writer

@Test
public void test2() throws IOException {
    String fileName = "C:\\Users\\DELL\\Desktop\\test\\ceshi1.txt";
    Path path = Paths.get(fileName);
    //从jdk7开始提供的方法
    //使用Files.writer创建一个文件并写入
    Files.write(path, "创建文件".getBytes(StandardCharsets.UTF_8));
    //追加写模式【这种模式必须确保文件已存在】
    Files.write(path, "创建文件".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
}

PrintWriter

@Test
public void test3() throws FileNotFoundException, UnsupportedEncodingException {
    String fileName = "C:\\Users\\DELL\\Desktop\\test\\ceshi2.txt";

    //JDK 1.5开始提供的方法
    try (PrintWriter writer = new PrintWriter(fileName, "UTF-8")) {
        writer.println("创建文件");
    }
}

File.createNewFile

@Test
public void test4() throws IOException {
    String fileName = "C:\\Users\\DELL\\Desktop\\test\\ceshi3.txt";

    File file = new File(fileName);

    //返回true 表示创建文件成功
    //false 表示文件已经存在
    if (file.createNewFile()) {
        System.out.println("文件创建成功");
    } else {
        System.out.println("文件已经存在不需要重复创建");
    }

    // 使用FileWriter写文件
    try (FileWriter writer = new FileWriter(file)) {
        writer.write("创建文件");
    }
}

FileOutputStream.writer(byte[] b)管道流

@Test
public void test5() throws IOException {
    String fileName = "C:\\Users\\DELL\\Desktop\\test\\ceshi4.txt";
    try (
        FileOutputStream fos = new FileOutputStream(fileName);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
        BufferedWriter bw = new BufferedWriter(osw);
    ) {
        bw.write("创建文件!!");
    }
}

Java IO之读取文件数据的6种方法

Files.lines返回Stream(Java 8)流式数据处理,按行读取
Files.readAllLines返回List(Java 8)
Files.readString读取String(Java11)文件最大 2G
Files.readAllBytes读取byte[](Java 7)文件最大 2G
BufferedReader经典方式

你可能感兴趣的:(一,Java,九,工作及问题,java,chrome,开发语言)