I’m new to java and I’m having a little problem with my code. There’s no error and such, it just keeps saying process finished but no output was displayed. The filename is correct as I’ve checked.
import java.nio.file.; import java.io.;
public class GuessingGame { public GuessingGame() { String filename = "C:\Users\angela\Documents\words.txt"; Path path = Paths.get(filename.toString()); try { InputStream input = Files.newInputStream(path); BufferedReader read = new BufferedReader(new InputStreamReader(input)); String word = null; while((word = read.readLine()) !=null) { System.out.println(word); } } catch(IOException ex) { } } public static void main (String[] args) { new GuessingGame(); } }
Advertisement
Answer
You are ignoring the exception and you don’t close the file. Save some typing by using the built-in input.transferTo()
for copying the file to System.out
, and pass on the exception for the caller to handle by adding throws IOException
to constructor and main
.
Replace your try-catch block with this try-with-resources, which handles closing the file after use:
try (InputStream input = Files.newInputStream(path)) { input.transferTo(System.out) ; }