英文:
I want to open a file for reading in the constructor. The file should be readable in any method without creating another reader object
问题
构造函数用于打开一个文件以进行读取操作。我有一个名为getNext()的方法,它返回文件的下一行内容,并以字符串数组的形式呈现。然而,它指出在构造函数中已创建的BufferedReader对象无法找到。
import java.io.*;
import java.util.*;
public class SNIDDb
{
private char delimiter;
private String name;
private BufferedReader br; // 添加一个私有成员变量用于保存BufferedReader对象
public SNIDDb(String name, char delimiter)
{
this.name = name;
this.delimiter = delimiter;
try
{
FileReader fr = new FileReader(name);
br = new BufferedReader(fr); // 初始化BufferedReader对象
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
public Boolean hasNext() throws Exception
{
return !(br.readLine() == null);
}
public String[] getNext() throws Exception
{
String c_line = "";
c_line = br.readLine();
String[] n_line = c_line.split(Character.toString(delimiter)); // 将delimiter转换为字符串并使用它进行分割
return n_line;
}
public void rewrite() throws Exception
{
br.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(name));
}
}
注意:上述翻译的代码进行了一些修改,包括添加了一个私有成员变量br
来保存BufferedReader
对象,以便在各个方法中都能够访问它。另外,在split()
方法中,我使用Character.toString(delimiter)
将delimiter
转换为字符串,以便正确地分割行。
英文:
The constructor opens a file for reading. I have a method called getNext() which returns the next line of the file in a String array. However it says that the BufferedReader object in already created in the constructor cannot be found
import java.io.;
import java.util.;
public class SNIDDb
{
private char delimiter;
private String name;
public SNIDDb(String name, char delimiter)
{
this.name=name;
this.delimiter=delimiter;
try
{
FileReader fr= new FileReader(name);
BufferedReader br= new BufferReader(fr);
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
public Boolean hasNext() throws Exception
{
return !(br.readLine()==null);
}
public String[] getNext() throws Exception
{
String c_line="";
c_line=br.readLine();
String[] n_line=c_line.split(delimiter);
return n_line;
}
public void rewrite() throws Exception
{
br.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(name));
}
答案1
得分: 0
br
是一个仅在构造函数内部可用的局部变量。你应该将它作为实例成员变量,就像delimiter
和name
一样。
英文:
br
is a local variable only available for use inside the constructor. You should make it an instance member variable like delimiter
and name
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论