在Java中使用Scanner类读取.txt文件

62
我正在开发一个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();
    }
 }
}

3
尝试添加 System.err.println(file.getAbsolutePath()); 来查看您尝试读取的确切文件。 - Roger Lindsjö
3
您无法打开一个 .txt 文件。 - eckes
@RogerLindsjö,非常感谢您的帮助。我成功找到了我的Mac上的绝对路径。它是/Users/myUsername/code/java/myRepoName。 - Evan Erickson
11个回答

71

在这里必须输入文件扩展名

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

34

使用以下代码来读取文件

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

}

这个应用程序正在逐行打印文件内容


4
为什么要创建一个从 System.in 读取的扫描器,然后再将其更改为从文件中读取? - VeraKozya
4
他正在从控制台读取一行内容,以获取用户想要读取的文件名称。为了简化代码,他只是重复使用相同的别名来引用两个扫描器。 - Anthony

12

这里有一些经过验证的工作方法;

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

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

7
  1. Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).

  2. Use the Class.getResource method to locate your file in the classpath - don't rely on the current directory:

    URL url = insertionSort.class.getResource("10_Random");
    
    File file = new File(url.toURI());
    
  3. Specify the absolute file path via command-line arguments:

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

在Eclipse中:

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

+1 建议正确处理路径的方法和更好的(args)执行此任务的一般方法。您还可以提及使用 try catch 处理无法打开文件的情况。 - Iskar Jarak

3
没有人提到一个事实,那就是你根本没有将任何内容输入到数组中。你只是将读取到的每个整数设置为“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]");
}

2
私有的无返回值方法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();
        }
    }
}

2
  1. 你需要指定完整的文件名,包括文件扩展名,例如10_Random.txt
  2. 如果想要不使用任何显式路径引用该文件,则该文件需要与可执行文件位于同一目录中。
  3. 顺便提一下,在读取int之前,需要检查是否存在int。使用hasNextLine()检查然后期望使用nextInt()获取int是不安全的。应该使用hasNextInt()来检查是否确实有一个int可以获取。当然,你可以自行决定是否严格遵守每行一个整数的规则。

1

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


1
请使用以下标签之一

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

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

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

0

你读取的文件必须与你指定的文件名完全一致:"10_random"不是"10_random.txt" 也不是 "10_random.blah",它必须与你所要求的精确匹配。你可以更改任意一个以使它们对齐,但务必确保它们匹配。在你使用的任何操作系统中显示文件扩展名可能会有所帮助。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接