简体   繁体   中英

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?

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);
      }
    }
  }
}

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();
    }

ps 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

好吧,如果您使用的是Mac, file.java<input.txt键入到终端文件file.java<input.txt然后输出到您键入以下内容的文件中: file.java>output.txt output.txt是不存在的文件,而input.txt是一个预先存在的文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM