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

Dani AI

Generated

The file format is simple: first line = count, remaining lines = words. Good suggestions already from (Scanner), (BufferedReader) and (close streams). Modern, concise and robust options are shown below — pick the one that fits your JVM and file size.

A simple, readable approach for small files (loads whole file into memory):

import java.nio.file.*;
import java.nio.charset.*;
import java.util.*;

Path p = Paths.get("words.txt");
List<String> lines = Files.readAllLines(p, StandardCharsets.UTF_8);
if (lines.isEmpty()) throw new IOException("empty file");
String header = lines.get(0).trim().replace("\\uFEFF", ""); // strip BOM if present
int n = Integer.parseInt(header);
List<String> wordsPart = lines.size() > 1 ? lines.subList(1, Math.min(lines.size(), n + 1)) : Collections.emptyList();
String[] words = wordsPart.toArray(new String[0]);
// handle wordsPart.size() < n (missing lines) or > n (extra lines ignored)

Notes and gotchas:

  • Files.readAllLines is fine for ~830 entries, but for much larger files use a streaming approach (Files.lines) to avoid high memory use.
  • Trim each line and consider skipping empty lines if the file may contain blanks.
  • Beware of BOMs on the first line; the code above removes it before parsing.
  • Always catch NumberFormatException and IOExceptions and decide how to handle fewer lines than the header (resize the array, throw an error, or pad with nulls).
  • Relative paths are resolved against the JVM working directory — use an absolute Path during testing if the file is not found.

If you want a Scanner-based variant (as suggested), use scanner.nextInt() for the count and then read tokens/lines into a List or preallocated String[]; prefer try-with-resources so streams close automatically (this addresses ’s closing concern).

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.