关于java中创建、写入文件的5种方式

216 篇文章 1 订阅

这篇文章主要介绍了java中创建、写入文件的5种方式,帮助大家更好的理解学习Java io的相关知识 。

在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的。

1

2

3

4

try(管道流、连接等实现了Closeable接口的类){

  //这里使用类对象操作

}

//用try()包含起来,就不用在finally里面自己手动的去 Object.close()了,会自动的关闭

1. Java 8 Files.newBufferedWriter

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@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实现的。同样提供追加写模式向已经存在的文件种追加数据。这种方式是实现文本文件简单读写最方便快捷的方式。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@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方法,可以实现一行一行的写文件。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@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 来完成文件的写操作。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

@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。

1

2

3

4

5

6

7

8

9

10

@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();

  }

}

以上就是java中创建、写入文件的5种方式的详细内容,希望对你有所帮助。

来源:微点阅读  https://www.weidianyuedu.com

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值