zoukankan      html  css  js  c++  java
  • 总结java中创建并写文件的5种方式

    在java中有很多的方法可以创建文件写文件,你是否真的认真的总结过?下面笔者就帮大家总结一下java中创建文件的五种方法。

    1. Files.newBufferedWriter(Java 8)
    2. Files.write(Java 7 推荐)
    3. PrintWriter
    4. File.createNewFile
    5. FileOutputStream.write(byte[] b) 管道流

    实际上不只这5种,通过管道流的排列组合,其实有更多种,但是笔者总结的这五种可以说是最常用及最佳实践,

    前提小知识

    以前我在写技术文章涉及到“流关闭”、“连接关闭”的时候,经常有人留言:“还写技术文章,写个流都不知道close()”,这种留言我遇到过无数回!
    在本文中大量的使用到了try-with-resources语法,这个语法真的是很久的了,但是的确还有小伙伴不知道(知道的小伙伴就略过吧)。我还是说一下,下文中的管道流不是我没close,是自动关闭close的。

    try(管道流、连接等实现了Closeable接口的类){
        //这里使用类对象操作
    }
    //用try()包含起来,就不用在finally里面自己手动的去 Object.close()了,会自动的关闭
    

    1. Java 8 Files.newBufferedWriter

    java8 提供的newBufferedWriter可以创建文件,并向文件内写入数据。可以通过追加写模式,向文件内追加内容。

    @Test
    void testCreateFile1() throws IOException {
       String fileName = "D:\data\test\newFile.txt";
    
       Path path = Paths.get(fileName);
       // 使用newBufferedWriter创建文件并写文件
       // 这里使用了try-with-resources方法来关闭流,不用手动关闭
       try (BufferedWriter writer =
                       Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
          writer.write("Hello World -创建文件!!");
       }
    
       //追加写模式
       try (BufferedWriter writer =
                    Files.newBufferedWriter(path,
                            StandardCharsets.UTF_8,
                            StandardOpenOption.APPEND)){
           writer.write("Hello World -字母哥!!");
       }
    }
    

    2. Java 7 Files.write

    下面的这种方式Files.write,是笔者推荐的方式,语法简单,而且底层是使用Java NIO实现的。同样提供追加写模式向已经存在的文件种追加数据。这种方式是实现文本文件简单读写最方便快捷的方式。

    @Test
    void testCreateFile2() throws IOException {
       String fileName = "D:\data\test\newFile2.txt";
    
       // 从JDK1.7开始提供的方法
       // 使用Files.write创建一个文件并写入
       Files.write(Paths.get(fileName),
                   "Hello World -创建文件!!".getBytes(StandardCharsets.UTF_8));
    
       // 追加写模式
       Files.write(
             Paths.get(fileName),
             "Hello World -字母哥!!".getBytes(StandardCharsets.UTF_8),
             StandardOpenOption.APPEND);
    }
    

    3. PrintWriter

    PrintWriter是一个比较古老的文件创建及写入方式,从JDK1.5就已经存在了,比较有特点的是:PrintWriter的println方法,可以实现一行一行的写文件。

    @Test
    void testCreateFile3() throws IOException {
       String fileName = "D:\data\test\newFile3.txt";
    
       // JSD 1.5开始就已经存在的方法
       try (PrintWriter writer = new PrintWriter(fileName, "UTF-8")) {
          writer.println("Hello World -创建文件!!");
          writer.println("Hello World -字母哥!!");
       }
    
       // Java 10进行了改进,支持使用StandardCharsets指定字符集
       /*try (PrintWriter writer = new PrintWriter(fileName, StandardCharsets.UTF_8)) {
    
          writer.println("first line!");
          writer.println("second line!");
    
       } */
    
    }
    

    4. File.createNewFile()

    createNewFile()方法的功能相对就比较纯粹,只是创建文件不做文件写入操作。 返回true表示文件成功,返回 false表示文件已经存在.可以配合FileWriter 来完成文件的写操作。

    @Test
    void testCreateFile4() throws IOException {
       String fileName = "D:\data\test\newFile4.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("Hello World -创建文件!!");
       }
    
    }
    

    5.最原始的管道流方法

    最原始的方式就是使用管道流嵌套的方法,但是笔者觉得这种方法历久弥新,使用起来非常灵活。你想去加上Buffer缓冲,你就嵌套一个BufferedWriter,你想去向文件中写java对象你就嵌套一个ObjectOutputStream。但归根结底要用到FileOutputStream。

    @Test
    void testCreateFile5() throws IOException {
       String fileName = "D:\data\test\newFile5.txt";
       try(FileOutputStream fos = new FileOutputStream(fileName);
          OutputStreamWriter osw = new OutputStreamWriter(fos);
          BufferedWriter bw = new BufferedWriter(osw);){
          bw.write("Hello World -创建文件!!");
          bw.flush();
       }
    }
    

    欢迎关注我的博客,里面有很多精品合集

    • 本文转载注明出处(必须带连接,不能只转文字):字母哥博客

    觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力! 。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。

  • 相关阅读:
    密码学与安全技术
    分布式系统核心问题
    虚拟机性能监控与故障处理工具
    垃圾收集器与内存分配策略
    Channel
    Buffer
    Reactor
    I/O简介
    HashMap
    装饰者模式
  • 原文地址:https://www.cnblogs.com/zimug/p/13575183.html
Copyright © 2011-2022 走看看