I apologize in advance if the solution is relatively obvious; however, the AP compsci curriculum at my highschool included practically no involvement with IO or file components. I've been trying to write an elementary flashcard program - thus it would be much more practical to read strings off a text file than add 100 objects to an array. My issue is that when I go to check the size and contents of the ArrayList at the end, it's empty. My source code is as follows:
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() );
}
}
My text file looks as thus:
Volare : To Fly
Velle : To Wish
Facere : To Do / Make
Trahere : To Spin / Drag
Odisse : To Hate
... et alia
My FlashCard class is very simplistic; it merely takes two Strings as parameter. The issue though is that the output whenever I run this is that nothing is printed except for the 0 printed in the main method, indicating that the ArrayList is empty. I thank you in advance for any help, as any would be appreciated.
einmain(), try printing the stack trace. You may be getting some exception that isn't caught by one of your other catch blocks.br.close()is inside thewhileloop and therefore will be called for each iteration of thewhileloop, which isn't what you want.new FileInputStreamwill throw an exception (which yourmainprogram then catches and ignores), before you get tofile.exists().