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

时间:2022-06-08 00:08:30

I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.

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

I am getting the following error messages:

我收到以下错误消息:

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)

I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.

我在我的“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();
    }
 }
}

11 个解决方案

#1


49  

You have to put file extension here

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

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

#2


18  

Use following codes to read the file

使用以下代码读取文件

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

}

-> This application is printing the file content line by line

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

#3


5  

  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:

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

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

In Eclipse:

  1. Choose "Run configurations"
  2. 选择“运行配置”

  3. Go to the "Arguments" tab
  4. 转到“参数”选项卡

  5. Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
  6. 将“c:/my/file/is/here/10_Random.txt.or.whatever”放入“程序参数”部分

#4


3  

here are some working and tested methods;

这里有一些工作和测试方法;

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


Here's another way to read entire file (without loop) using Scanner class

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

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

#5


2  

No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.

似乎没有人解决过你根本没有输入任何东西的事实。您将每个读取的int设置为“i”然后输出它。

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

Something to this effect will keep setting values of the array to the next integer read.

此效果将使数组的值设置为下一个整数读取。

Than another for loop can display the numbers in the array.

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

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

#6


1  

  1. You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
  2. 您需要指定确切的文件名,包括文件扩展名,例如10_Random.txt。

  3. The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
  4. 如果要在没有任何显式路径的情况下引用该文件,则该文件需要与可执行文件位于同一目录中。

  5. While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
  6. 虽然我们正在使用它,但您需要在读取int之前检查int。检查hasNextLine()然后期望带有nextInt()的int是不安全的。您应该使用hasNextInt()来检查实际上是否有一个要抓取的int。当然,您选择强制执行每行一个整数规则的严格程度取决于您。

#7


1  

File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file. Please log the file.getAbsolutePath() to verify that file is correct.

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

#8


1  

private void loadData() {

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

#9


0  

The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.

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

Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.

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

#10


0  

At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.

首先检查文件地址,它必须位于.java文件旁边或者在classpath环境变量中定义的任何地址中。当你检查这个,然后尝试下面。

  1. you must use a file name by it's extension in File object constructor, as an example:

    你必须在File对象构造函数中使用它的扩展名作为文件名,例如:

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

    文件myFile = new File(“test.txt”);

  2. but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:

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

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

    扫描仪sc =新扫描仪(Paths.get(“test.txt”));

in this way you must import java.nio.file.Paths as well.

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

#11


0  

You should use either

你应该使用其中之一

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

Or

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

Relative to the project folder in Eclipse.

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

#1


49  

You have to put file extension here

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

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

#2


18  

Use following codes to read the file

使用以下代码读取文件

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

}

-> This application is printing the file content line by line

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

#3


5  

  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:

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

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

In Eclipse:

  1. Choose "Run configurations"
  2. 选择“运行配置”

  3. Go to the "Arguments" tab
  4. 转到“参数”选项卡

  5. Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
  6. 将“c:/my/file/is/here/10_Random.txt.or.whatever”放入“程序参数”部分

#4


3  

here are some working and tested methods;

这里有一些工作和测试方法;

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


Here's another way to read entire file (without loop) using Scanner class

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

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

#5


2  

No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.

似乎没有人解决过你根本没有输入任何东西的事实。您将每个读取的int设置为“i”然后输出它。

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

Something to this effect will keep setting values of the array to the next integer read.

此效果将使数组的值设置为下一个整数读取。

Than another for loop can display the numbers in the array.

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

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

#6


1  

  1. You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
  2. 您需要指定确切的文件名,包括文件扩展名,例如10_Random.txt。

  3. The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
  4. 如果要在没有任何显式路径的情况下引用该文件,则该文件需要与可执行文件位于同一目录中。

  5. While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
  6. 虽然我们正在使用它,但您需要在读取int之前检查int。检查hasNextLine()然后期望带有nextInt()的int是不安全的。您应该使用hasNextInt()来检查实际上是否有一个要抓取的int。当然,您选择强制执行每行一个整数规则的严格程度取决于您。

#7


1  

File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file. Please log the file.getAbsolutePath() to verify that file is correct.

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

#8


1  

private void loadData() {

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

#9


0  

The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.

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

Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.

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

#10


0  

At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.

首先检查文件地址,它必须位于.java文件旁边或者在classpath环境变量中定义的任何地址中。当你检查这个,然后尝试下面。

  1. you must use a file name by it's extension in File object constructor, as an example:

    你必须在File对象构造函数中使用它的扩展名作为文件名,例如:

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

    文件myFile = new File(“test.txt”);

  2. but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:

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

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

    扫描仪sc =新扫描仪(Paths.get(“test.txt”));

in this way you must import java.nio.file.Paths as well.

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

#11


0  

You should use either

你应该使用其中之一

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

Or

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

Relative to the project folder in Eclipse.

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