java 文件保存,如何在java中保存文件

I am trying to create a file from a log report. To save I have created a button. When the button is pushed, the following code is executed.

public void SAVE_REPORT(KmaxWidget widget){//save

try {

String content = report.getProperty("TEXT");

File file = new File("logKMAX.txt");

// if file doesnt exists, then create it

if (!file.exists()) {

file.createNewFile();

}

FileWriter fw = new FileWriter(file.getAbsoluteFile());

BufferedWriter bw = new BufferedWriter(fw);

bw.write(content);

bw.close();

} catch (IOException e) {

e.printStackTrace();

}

} //SAVE_REPORT

I have no compile errors, but again there is no file save in the directory that I have the aforementioned code.

Any idea on what might be wrong?

解决方案

Use the new file API. For one, in your program, you don't verify the return value of .createNewFile(): it doesn't throw an exception on failure...

With the new file API, it is MUCH more simple:

public void saveReport(KmaxWidget widget)

throws IOException

{

final String content = report.getProperty("TEXT");

final Path path = Paths.get("logKMAX.txt");

try (

final BufferedWriter writer = Files.newBufferedWriter(path,

StandardCharsets.UTF_8, StandardOpenOption.CREATE);

) {

writer.write(content);

writer.flush();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值