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??

Recommended Answers

All 3 Replies

Look at the Scanner class for a simple way to read a file.

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) { }

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();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.