【问题标题】:Reading a .txt file using Scanner class in Java使用 Java 中的 Scanner 类读取 .txt 文件
【发布时间】:2023-03-15 16:29:01
【问题描述】:

我正在开发一个 Java 程序,它逐行读取文本文件,每个文件都有一个数字,将每个数字放入一个数组中,然后尝试使用插入排序对数组进行排序。我需要帮助让程序读取文本文件。

我收到以下错误消息:

java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)

我的“src”“bin”和主项目文件夹中有 .txt 文件的副本,但它仍然找不到该文件。顺便说一下,我正在使用 Eclipse。

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

public class insertionSort {

public static void main(String[] args) {

    File file = new File("10_Random");

    try {

        Scanner sc = new Scanner(file);

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

【问题讨论】:

  • 尝试添加 System.err.println(file.getAbsolutePath());以准确查看您尝试读取的文件。
  • 您没有打开 .txt 文件。
  • @RogerLindsjö 这对我帮助很大。我能够在mac上找到我的绝对路径。它是 /Users/myUsername/code/java/myRepoName。

标签: java file-io java.util.scanner


【解决方案1】:

你必须把文件扩展名放在这里

File file = new File("10_Random.txt");

【讨论】:

    【解决方案2】:

    使用以下代码读取文件

    import java.io.File;
    import java.util.Scanner;
    
    public class ReadFile {
    
        public static void main(String[] args) {
    
            try {
                System.out.print("Enter the file name with extension : ");
    
                Scanner input = new Scanner(System.in);
    
                File file = new File(input.nextLine());
    
                input = new Scanner(file);
    
    
                while (input.hasNextLine()) {
                    String line = input.nextLine();
                    System.out.println(line);
                }
                input.close();
    
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
    }
    

    ->此应用程序正在逐行打印文件内容

    【讨论】:

    • 你为什么要创建一个扫描仪并将其设置为从 System.in 读取,然后将其更改为从文件读取?
    • 他正在从控制台读取一行以获取用户要读取的文件的名称。他只是为两个扫描仪重用相同的别名来简化代码。
    【解决方案3】:

    这里有一些可行且经过测试的方法;

    using Scanner

    package io;
    
    import java.io.File;
    import java.util.Scanner;
    
    public class ReadFromFileUsingScanner {
        public static void main(String[] args) throws Exception {
            File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
            Scanner sc=new Scanner(file);
            while(sc.hasNextLine()){
                System.out.println(sc.nextLine());
            }
        }
    }
    


    这是使用 Scanner 类读取整个文件(无循环)的另一种方法

    package io;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class ReadingEntireFileWithoutLoop {
        public static void main(String[] args) throws FileNotFoundException {
            File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
            Scanner sc=new Scanner(file);
            sc.useDelimiter("\\Z");
            System.out.println(sc.next());
        }
    }
    

    使用BufferedReader

     package io;
    import java.io.*;
    public class ReadFromFile2 {
        public static void main(String[] args)throws Exception {
            File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
            BufferedReader br=new BufferedReader(new FileReader(file));
            String st;
            while((st=br.readLine())!=null){
                System.out.println(st);
            }
        }
    }
    

    using FileReader

    package io;
    import java.io.*;
    public class ReadingFromFile {
        public static void main(String[] args) throws Exception {
            FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
            int i;
            while((i=fr.read())!=-1){
                System.out.print((char) i);
            }
        }
    }
    

    【讨论】:

      【解决方案4】:
      1. 确保文件名正确(正确的大小写、匹配的扩展名等 - 如前所述)。

      2. 使用Class.getResource 方法在类路径中定位您的文件 - 不要依赖当前目录:

        URL url = insertionSort.class.getResource("10_Random");
        
        File file = new File(url.toURI());
        
      3. 通过命令行参数指定绝对文件路径:

        File file = new File(args[0]);
        

      在 Eclipse 中:

      1. 选择“运行配置”
      2. 转到“参数”标签
      3. 将“c:/my/file/is/here/10_Random.txt.or.whatever”放入“程序参数”部分

      【讨论】:

      • +1 用于建议正确处理路径的方法和通常执行此任务的更好方法(args)。您也可以提及 try catch 来处理打开文件失败的问题。
      【解决方案5】:

      似乎没有人解决您根本没有在数组中输入任何内容的事实。您正在将读取的每个 int 设置为“i”,然后将其输出。

      for (int i =0 ; sc.HasNextLine();i++)
      {
          array[i] = sc.NextInt();
      }
      

      具有这种效果的东西会将数组的值设置为下一个整数读取。

      比另一个for循环可以显示数组中的数字。

      for (int x=0;x< array.length ; x++)
      {
          System.out.println("array[x]");
      }
      

      【讨论】:

        【解决方案6】:
        1. 您需要指定确切的文件名,包括文件扩展名,例如10_Random.txt
        2. 如果您想在没有任何明确路径的情况下引用该文件,则该文件需要与可执行文件位于同一目录中。
        3. 在我们进行此操作时,您需要先检查int,然后再阅读int。使用hasNextLine() 进行检查,然后期待intnextInt() 是不安全的。您应该使用hasNextInt() 来检查是否确实有一个int 可供抓取。当然,您选择执行每行一个整数规则的严格程度取决于您。

        【讨论】:

          【解决方案7】:

          私有 void loadData() {

              Scanner scanner = null;
              try {
                  scanner = new Scanner(new File(getFileName()));
                  while (scanner.hasNextLine()) {
                      Scanner lijnScanner = new Scanner(scanner.nextLine());
          
                      lijnScanner.useDelimiter(";");
                      String stadVan = lijnScanner.next();
                      String stadNaar = lijnScanner.next();
                      double km = Double.parseDouble(lijnScanner.next());
          
                      this.voegToe(new TweeSteden(stadVan, stadNaar), km);
          
                  }
              } catch (FileNotFoundException e) {
                  throw new DbException(e.getMessage(), e);
              } finally {
                  if(scanner != null){
                      scanner.close();
                  }
              }
          }
          

          【讨论】:

            【解决方案8】:

            文件路径似乎是一个问题,请确保该文件存在于正确的目录中或提供绝对路径以确保您指向正确的文件。 请记录 file.getAbsolutePath() 以验证文件是否正确。

            【讨论】:

              【解决方案9】:

              你应该使用任何一个

              File file = new File("bin/10_Random.txt");
              

              或者

              File file = new File("src/10_Random.txt");
              

              相对于 Eclipse 中的项目文件夹。

              【讨论】:

                【解决方案10】:

                您读入的文件必须与您指定的文件名完全相同:"10_random" 不是“10_random.txt”而不是“10_random.blah”,它必须与您要求的完全匹配。您可以更改其中任何一个以匹配,以使它们对齐,但请确保它们对齐。在您使用的任何操作系统中显示文件扩展名可能会有所帮助。

                另外,对于文件位置,它必须与作为编译结果的最终可执行文件(.class 文件)位于工作目录(同一级别)中。

                【讨论】:

                  【解决方案11】:

                  首先检查文件地址,它必须在您的.java 文件旁边或您在classpath 环境变量中定义的任何地址中。当您检查此内容时,请尝试以下操作。

                  1. 您必须在 File 对象构造函数中使用文件名的扩展名,例如:

                    File myFile = new File("test.txt");

                  2. 但是有一个更好的方法可以通过传递文件名绝对地址在 Scanner 对象中使用它,例如:

                    Scanner sc = new Scanner(Paths.get("test.txt"));

                  这样你也必须导入java.nio.file.Paths

                  【讨论】:

                    【解决方案12】:

                    顺便说一句,设置字符编码也是值得的:

                    Scanner scanner = new Scanner(new File("C:\\tmp\\edit1.txt"), "UTF-16");
                    

                    【讨论】:

                    • 由于这不能回答问题,因此更适合发表评论。遗憾的是,新用户无法发表评论。
                    猜你喜欢
                    • 1970-01-01
                    • 2017-01-18
                    • 2021-01-04
                    • 2018-11-08
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-08-21
                    • 1970-01-01
                    相关资源
                    最近更新 更多