java怎么写文件_如何使用java写文件

完整代码:

在下面的示例中, 我们将一串字符串写入到一个文件。

为了将String转换为字节数组, 我们使用了字符串类的getBytes () 方法.

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

public class WriteFileDemo {

public static void main(String[] args) {

FileOutputStream fos = null;

File file;

String mycontent = "需要写入文件的数据" + " to be written into the file";

try {

// 指定写入文件的路径

file = new File("D:/myfile.txt");

fos = new FileOutputStream(file);

/* 先检测文件是否存在,如果不存在则先创建*/

if (!file.exists()) {

file.createNewFile();

}

/*

* 字符串的内容没法直接写到文件,我们需要先使用getBytes转换为bytes。

*/

byte[] bytesArray = mycontent.getBytes();

fos.write(bytesArray);

fos.flush();

System.out.println("File Written Successfully");

} catch (IOException ioe) {

ioe.printStackTrace();

} finally {

try {

if (fos != null) {

fos.close();

}

} catch (IOException ioe) {

System.out.println("Error in closing the Stream");

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值