I want to open a file for reading in the constructor. The file should be readable in any method without creating another reader object

huangapple go评论78阅读模式
英文:

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是一个仅在构造函数内部可用的局部变量。你应该将它作为实例成员变量,就像delimitername一样。

英文:

br is a local variable only available for use inside the constructor. You should make it an instance member variable like delimiter and name.

huangapple
  • 本文由 发表于 2020年5月30日 10:24:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/62097055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定