因为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.
}
答案 0 :(得分:2)
您可以简单地将对作者的引用传递给每个方法,例如......
private void WriteStudentMarks(BufferedWriter writer){
然后只需调用方法
BufferedWriter writer = null;
//...
WriteStudentMarks(writer);
//...
您也可以希望通读Code Conventions for the Java Programming Language,这样可以让人们阅读您的代码......