D. Snow
D. Snow

Reputation: 129

Java read file using Scanner

I can read file using java.io and java.util.Scanner but I don't know how to read file using only java.util.Scanner:

import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
        Scanner sc = new Scanner(new File(filePath));
        int a, b;
        a = sc.nestInt();
        b = sc.nextInt();
    }
}

Can someone help?

Upvotes: 0

Views: 12639

Answers (3)

gomisha
gomisha

Reputation: 2922

Since Scanner requires a java.io.File object, I don't think there's a way to read with Scanner only without using any java.io classes.

Here are two ways to read a file with the Scanner class - using default encoding and an explicit encoding. This is part of a long guide of how to read files in Java.

Scanner – Default Encoding

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile_Scanner_NextLine {
  public static void main(String [] pArgs) throws FileNotFoundException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    try (Scanner scanner = new Scanner(file)) {
      String line;
      boolean hasNextLine = false;
      while(hasNextLine = scanner.hasNextLine()) {
        line = scanner.nextLine();
        System.out.println(line);
      }
    }
  }
}

Scanner – Explicit Encoding

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile_Scanner_NextLine_Encoding {
  public static void main(String [] pArgs) throws FileNotFoundException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    //use UTF-8 encoding
    try (Scanner scanner = new Scanner(file, "UTF-8")) {
      String line;
      boolean hasNextLine = false;
      while(hasNextLine = scanner.hasNextLine()) {
        line = scanner.nextLine();
        System.out.println(line);
      }
    }
  }
}

Upvotes: 3

Tzach Oren
Tzach Oren

Reputation: 106

if you want to read the file until the end:

String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
File file = new File(filePath);

    try {

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {
            int i = sc.nextInt();
            System.out.println(i);
        }
        sc.close();
    } 
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }

p.s If every line have only Integer I suggest you to use Integer.parseInt(sc.readLine());
instead of sc.nextInt();

If you cant read please send me file Context

Upvotes: 0

Josh Heaps
Josh Heaps

Reputation: 345

Well, if you are using a Mac, you type this into the terminal file.java<input.txt and to output to a file you type this: file.java>output.txt output.txt is a non-existing file, while input.txt is a pre-existing file.

Upvotes: -1

Related Questions