I was hoping someone could give me the code to read and then to system print out the words in the text file.

The textfile contains:
One,
Two,
Three,

I'm new to IO readers so this would help alot as I'm having trouble reprinting the information out.

Dani AI

Generated

asked for code to read a text file and print the words. The file sample has tokens with trailing commas ("One,", "Two,", "Three,") so the simplest robust approach is: read lines safely, split each line on commas and/or whitespace, trim and filter out empty tokens, then print each token. Use try-with-resources to ensure streams are closed and handle IOException instead of swallowing it.

Note on the existing replies: 's pointer to search is fine as general advice. The snippet from has a syntax error and some design issues — it mixes a Scanner with a BufferedReader (you only need one), and it leaves exception blocks empty. Avoid silent failures and prefer concise, modern APIs.

Example approach (Java 8+), using a stream, splitting on commas or whitespace and skipping empty results:

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

try (Stream<String> lines = Files.lines(Paths.get("fileToRead.txt"), StandardCharsets.UTF_8)) {
    lines
        .flatMap(line -> Arrays.stream(line.split("[,\\s]+")))
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .forEach(System.out::println);
} catch (IOException e) {
    System.err.println("Failed to read file: " + e.getMessage());
}

Extra tips: if words may include punctuation you want to keep (like apostrophes), use a more specific split or strip only leading/trailing punctuation with replaceAll. For true CSVs or quoted fields, use a CSV library (OpenCSV). If you get a file-not-found, check the working directory or use an absolute path and always specify the correct charset (UTF-8 is usually safest).

Recommended Answers

All 2 Replies

Google java read text file then google System.out.println

try {
	BufferedReader read= new BufferedReader(new FileReader
					           (new File("fileToRead.txt")));
	Scanner fileReader = new Scanner(read);
		
	while(fileReader.hasNext()){
		System.out.println(fileReader.nextLine();			
	}
	fileReader.close();
}catch (FileNotFoundException fileNotFound) {
} catch (IOException ioEx){}
commented: Don't give people code -1
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.