0

ive been looking up, and their seems to be many way to read from a file. my question is, how do you read from a file. the file setup is like this.... the first line is a number(830) representing number of words, next lines are words.. the file looks like this.

**830**
cooking
English
weather
..
..
etc

i want to read the words in a string array by creating a string object.. BUT how do i read the data first??

4
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by Aviras
0
try { 
		BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
     
		String line = "";
		while ((line = reader.readLine()) != null) {
			//This will read each line of the file sequentially.
		}
     
		reader.close();
	} catch (Exception ex) { }

Edited by Jaydenn: n/a

0

In addition to what Jaydenn said, it is advisable to close the streams in the 'finally' section. That way, in case an error is thrown, the stream will still close. As it is now, you'll have bad stream control.

So:

BufferedReader reader = null;
try { 
		reader = new BufferedReader(new FileReader("file.txt"));
     
		String line = "";
		while ((line = reader.readLine()) != null) {
			//This will read each line of the file sequentially.
		}
} catch (Exception ex) {
} finally{
      reader.flush();
      reader.close();
}

Edited by Aviras: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.