java 中创建并且写文件的几种方式(java io 基础)

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. Files.write(Java7)

在这里插入图片描述

这种方式是实现文本文件简单读写最方便快捷的方式。

@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”)) {

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值