Question

how do you load text from a txt file in java

how do you load text from a txt file in java

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.io.*;
import java.util.Scanner;
public class ReadText {
  public static void main(String[] args) throws IOException {
    String fileName;
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter file name: ");
    fileName = scanner.nextLine();
    File file = new File(fileName);
    try {
      // open the file
      Scanner scan = new Scanner(file);
      // if file has contents to read
      // loop to read the contents of the file
      String s;
      while(scan.hasNext()) {
        s = scan.nextLine()+" ";
        System.out.println(s);
      }
      scan.close();
      // close the Scanner object
    } catch (FileNotFoundException e) {
      // catch the exception if file not present
      System.out.println("File " + file.getName() + " not present ");
      System.exit(0);
    }
  }
}
Add a comment
Know the answer?
Add Answer to:
how do you load text from a txt file in java
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT