java - Java写入文件 - 使用类
问题描述
我在How to append text to an existing file in Java中阅读了与我类似的主题,并在那里尝试了解决方案,不幸的是,他们都没有回答我的具体情况。
我将对文件进行大量更改,因此我认为我将创建方法,该方法将返回PrintWriter
对象,我可以通过执行在该对象上进行更改writer.prinln("text");
private static PrintWriter WriteToFile() {
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("smrud.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
// out.println("the text");
return out;
}
catch( IOException e ){
return null;
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
}
所以在我的主要方法中,我调用了这个方法
PrintWriter writer = WriteToFile();
然后我正在做出改变
writer.println("the text2");
我正在关闭 writer 以将更改保存到磁盘:
writer.close();
不幸的是,我没有看到任何变化。当我将更改放入WriteToFile()
方法中时,我会看到更改:
private static void WriteToFile() {
PrintWriter out = null;
BufferedWriter bw = null;
FileWriter fw = null;
try{
fw = new FileWriter("smrud.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
}
catch( IOException e ){
// File writing/opening failed at some stage.
}
finally{
try{
if( out != null ){
out.close(); // Will close bw and fw too
}
else if( bw != null ){
bw.close(); // Will close fw too
}
else if( fw != null ){
fw.close();
}
else{
// Oh boy did it fail hard! :3
}
}
catch( IOException e ){
// Closing the file writers failed for some obscure reason
}
}
}
但是这个方法 open FileWriter
,BufferedWriter
每次PrintWriter
它都会被执行,我想通过返回PrintWriter
main 方法然后执行writer.println("text");
并在一段时间后关闭它来避免这种情况,writer.close();
但这不起作用。
任何建议将不胜感激。
解决方案
所有的作者都是封闭的,WriteToFile
所以当PrintWriter
对象被返回时它不会写任何东西。
您将不得不扩大范围PrintWriter
并在方法之外对其进行管理WriteToFile
。
有点像:
public static void main(String[] args) {
try (PrintWriter printWriter = createWriter()) {
printWriter.println("Line 1");
printWriter.println("Line 2");
} catch (IOException e) {
e.printStackTrace();
}
}
private static PrintWriter createWriter() throws IOException {
return new PrintWriter(new FileWriter("smrud.txt", true));
}
推荐阅读
- php - 移动上传的文件在 PHP 中不起作用
- javascript - 回调后如何将值返回给主函数
- android - android.view.InflateException 仅在 android 8.1 上发生
- c# - 优化重复代码
- mongodb-java - 使用编解码器时查找错误
- sql-server - SQL Server 2016 存储过程语法错误
- c# - 无法在 VS 2017 (15.7.5) 上运行.net core 2.1 应用程序
- mysql - mysqld修改pid
- matplotlib - %matplotlib 笔记本不尊重 figure.facecolor
- python - 在 Python 中创建字典时如何处理重复值?