【发布时间】: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