有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。scanner使用scanner读取Java文件

我可以使用java.iojava.util.Scanner读取文件,但我不知道如何仅使用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();
    }
}

有人能帮忙吗


共 (3) 个答案

  1. # 1 楼答案

    好的,如果您使用的是Mac,那么您可以在终端file.java<input.txt中键入该文件,并将其输出到一个文件中:file.java>output.txt{}是一个不存在的文件,而input.txt是一个预先存在的文件

  2. # 2 楼答案

    因为扫描器需要一个java。木卫一。文件对象,我不认为有一种只使用Scanner而不使用任何java的方法。io类

    这里有两种使用Scanner类读取文件的方法-使用默认编码和显式编码。这是如何read files in Java的长指南的一部分

    扫描仪–默认编码

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

    扫描仪-显式编码

    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);
          }
        }
      }
    }
    
  3. # 3 楼答案

    如果要一直读取文件,请执行以下操作:

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

    如果每一行只有整数,我建议你使用 整数parseInt(sc.readLine())
    而不是sc.nextInt()

    如果您无法阅读,请发送文件上下文给我