Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Scanner class. Show all posts
Showing posts with label Scanner class. Show all posts

Thursday, 22 November 2018

Read Text File in Java using Scanner Class

 Previously I have posted about reading text file using FileInputStream and BufferedReader. This post shows how to read text files in java using the Scanner class.


This is a sample text file


and this is the java code to read text files using the Scanner class

  1. package client;
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.util.Scanner;
  5. public class ReadFileScn {
  6. public ReadFileScn() {
  7. super();
  8. }
  9. public static void main(String[] args) {
  10. // Absolute path of file that you want to read
  11. File f = new File("D:/sampleFile.txt");
  12. Scanner s = null;
  13. try {
  14. s = new Scanner(f);
  15. } catch (FileNotFoundException e) {
  16. }
  17. //Iterate over file content
  18. while (s.hasNextLine())
  19. System.out.println(s.nextLine());
  20. }
  21. }

Execute this java code

Output is


Cheers 🙂 Happy Learning

Monday, 5 October 2015

Allow user input in Jdeveloper for Java applications, Using Java Scanner Class to take input from console

Sometimes we have to take input from Keyboard when we use Scanner or BufferedReader class.
and to take input from Jdeveloper we have to change a setting to allow user input in Jdeveloper.

Let's take an example of java.util.Scanner class-

package client;

import java.util.Scanner;

public class UserInput {
    public UserInput() {
        super();
    }

    public static void main(String[] args) {
        System.out.println("Please Enter your Name-");
        Scanner sc = new Scanner(System.in);
        String name = sc.next();
        System.out.println("Your Name is " + name);
    }

}