java如何使用new BufferedWriter(new FileWriter())的一个实例写入文件;用不同的方法
因为BufferWritter
在try-catch块中,我不能在不创建新文件的情况下在单独的方法中使用相同的实例。我不想从文件中读取和修改信息,因为这可能会与此程序的未来开发冲突
因此,我的问题是如何在不创建BufferWritter
的新实例的情况下写入同一个文件
private void writeStudentInfo(){
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("C:/" +
this.getStudentRegistrationNumber() + ".txt", true));
// Write to file here
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
第二种方法:
private void WriteStudentMarks(){
//I want to use the same instance of BufferWritter in this method for writtng.
// So I can use the 'writer' object to continue writting into the file.
}
# 1 楼答案
您可以简单地将引用传递给每个方法的编写器,例如
然后简单地调用该方法
您可能还希望通读Code Conventions for the Java Programming Language,这将使人们更容易阅读您的代码