The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Re: Copying a file into a vector

Posted by Brian Sanders on October 11, 2001 at 10:49 AM

Hi all. I am trying to read the contents of a text file into a vector, but am having some grief. My method for reading the file and a sample of the contents of the file are below. Can someone point me in the right direction with this? Thanks heaps.

Assuming that the class "SimpleReader" that you're using works as expected, I can see two problems with the code listing:

(original listing)

public void readFile() {
try {
SimpleReader inFile = new SimpleReader("Invent.txt");
while (!inFile.EOF()) {
String inventory = inFile.getString();
} catch (FileNotFoundException e) {
System.err.println("File Not Found");
} catch (IOException e) {

The first problem I see is that the String value "inventory" is never added to the Vector. The second problem I see is that the reader.close() method is called within the while loop. This will close the reader after the first line of the file is read.

In general, it is better form to use a finally block to close any file streams you may use. Using code of this form will always keep you out of trouble:

SomeReader reader = null;
reader = new SomeReader(...);
while (reader.hasMoreData())
//do something with the data
catch (IOException e)
//handle exception
//this code will be run regardless of whether the above succeeds or fails
if (reader != null)

My last observation is that this code looks A LOT like a project for a school course. The resources of the internet are wonderful for answering your programming questions, but your professors and teaching assistants really should be your first choice for this sort of thing; your future is too important to risk academic misconduct charges. My apologies if this situation is not applicable to your situation.


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us