【问题标题】:Issue with text file conversion to arraylist文本文件转换为 arraylist 的问题
【发布时间】:2014-10-01 08:26:53
【问题描述】:

如果解决方案比较明显,我提前道歉;但是,我高中的 AP compsci 课程几乎不涉及 IO 或文件组件。我一直在尝试编写一个基本的闪存卡程序 - 因此从文本文件中读取字符串比将 100 个对象添加到数组中要实用得多。我的问题是,当我最后检查 ArrayList 的大小和内容时,它是空的。我的源代码如下:

public class IOReader
{
  static ArrayList<FlashCard> cards = new ArrayList<FlashCard>();
  static File file = new File("temp.txt");

  public static void fillArray() throws FileNotFoundException, IOException
  {
    FileInputStream fiStream = new FileInputStream(file);
    if(file.exists())
    {
      try( BufferedReader br = new BufferedReader( new InputStreamReader(fiStream) )
      {
        String line;
        String[] seperated;
        while( (line = br.readLine()) != null)
        {
          try
          {
            seperated = line.split(":");
            String foreign = seperated[0];
            String english = seperated[1];
            cards.add( new FlashCard(foreign, english) );
            System.out.println(foreign + " : " + english);
          }
          catch(NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsException e)
          {
            e.printStackTrace();
          }
          finally{ 
            br.close(); 
          }
        }
      }
    }
    else{
      System.err.print("File not found");
      throw new FileNotFoundException();
    }
  }
  public static void main(String[] args)
  {
    try{
      fillArray();
    }
    catch (Exception e){}
    for(FlashCard card: cards)
      System.out.println( card.toString() );
    System.out.print( cards.size() );
  }
}

我的文本文件如下所示:

Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate
... et alia

我的 FlashCard 类非常简单;它只需要两个字符串作为参数。但问题是,每当我运行它时,除了在 main 方法中打印的 0 之外,什么都没有打印,这表明 ArrayList 是空的。我提前感谢您的任何帮助,我们将不胜感激。

【问题讨论】:

  • 您可能过早地关闭了缓冲阅读器。在 try-catch 构造之后,您最终将其关闭。然而,这意味着在 while 循环的第二次迭代中,bufferedreader 已经关闭。完成 while 循环后关闭它。但这并不能完全解决问题,因为它没有解释为什么循环中什么都没有打印出来。
  • 第一印象:不要忽略main() 中的异常e,而是尝试打印堆栈跟踪。您可能会遇到一些其他 catch 块没有捕获的异常。
  • Mshnik 是对的:br.close()while 循环内,因此将在 while 循环的每次迭代中调用,这不是您想要的。
  • 我猜它找不到文件。问题是new FileInputStream 会在你到达file.exists() 之前抛出一个异常(你的main 程序会捕获并忽略它)。
  • @Chris Dare,我知道数组列表的大小,如果你想知道的话,我可以发布我的答案,我可以向你解释发生了什么

标签: java file-io arraylist bufferedreader java-io


【解决方案1】:

需要考虑的几点:

  1. 在您的fillArray() 中很好地抛出异常并在代理中捕获它们 你程序的一部分是main(),所以你在fillArray()中的代码会更多 可读且不会隐藏异常。
  2. 我认为没有必要检查文件是否存在,因为如果不存在 存在时,将抛出异常并使用main() 函数。
  3. 我使用 Igal 类而不是 FlashCard 类,它与您的 FlashCard 类相同

Igal 类的代码:

public class Igal {
    private String st1;
    private String st2;

public Igal(String s1, String s2){
    st1 = s1;
    st2 = s2;
}



/**
 * @return the st1
 */
public String getSt1() {
    return st1;
}

/**
 * @param st1 the st1 to set
 */
public void setSt1(String st1) {
    this.st1 = st1;
}

/**
 * @return the st2
 */
public String getSt2() {
    return st2;
}

/**
 * @param st2 the st2 to set
 */
public void setSt2(String st2) {
    this.st2 = st2;
}

@Override
public String toString(){
    return getSt1() + " " + getSt2();
}

}

代码:

static List<Igal> cards = new ArrayList<>();
static File file = new File("C:\\Users\\xxx\\Documents\\NetBeansProjects\\Dictionary\\src\\temp.txt");

public static void fillArray() throws FileNotFoundException, IOException {

        FileInputStream fiStream = new FileInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(fiStream));
        String line;
        String[] seperated;

        while ((line = br.readLine()) != null) {
            seperated = line.split(":");
            String foreign = seperated[0];
            String english = seperated[1];
            System.out.println(foreign + " : " + english);
           Igal fc = new Igal(foreign, english);
           cards.add(fc);
      }
 }

public static void main(String[] args) {
    try {
        fillArray();
    } catch (IOException e) {
        System.out.println(e);
    }
    System.out.println("------------------");
    for (Igal card : cards) {
        System.out.println(card.toString());
    }
     System.out.print("the size is " + cards.size()+"\n");

temp.txt内容如下

Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate

输出:

------------------
Volare   To Fly
Velle   To Wish
Facere   To Do / Make
Trahere   To Spin / Drag
Odisse   To Hate
the size is 5

【讨论】:

  • 非常感谢,这解决了我在运行时遇到的错误 :-)。程序以现在应该的方式运行!
  • @ChrisDare 如果我的回答有帮助,你能告诉我
猜你喜欢
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 2018-05-16
  • 2019-11-02
  • 2013-10-03
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多