-1

我不明白如何从.txt下面的文件中读取数据。

static final String DATA_PATH = "DataFile.txt";

public static void main(String[] args) {

    Scanner fileReader = null;
    try {

        fileReader = new Scanner(new File(DATA_PATH));
        //Print out a trace of the program as it is running
        System.out.println("Debug: Scanner is open "+fileReader);
    } catch (FileNotFoundException e) {
        // If the file is not there, an exception will be thrown and the program flow
        // will directed here.  An error message is displayed and the program stops.
        System.out.println("The file "+DATA_PATH+" was not found!");
        System.out.println("The program terminates now.");
        System.exit(0);
    }
4

1 回答 1

1

这是使用扫描仪读取文件的示例。因此,您应该导入三个重要的包,它们是:

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

之后,您将创建文件对象以及文件的名称参数。然后,创建扫描仪对象。最后,您可以使用 while 循环逐行读取或任何您想要的。

 public class ScannerReadFile {
    public static void main(String[] args) {
        //
        // Create an instance of File for data.txt file.
        //
        File file = new File("data.txt");

        try {
            //
            // Create a new Scanner object which will read the data 
            // from the file passed in. To check if there are more 
            // line to read from it we check by calling the 
            // scanner.hasNextLine() method. We then read line one 
            // by one till all line is read.
            //
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

所以,你可以试着从我这里提到的代码开始,多练习!来自网站上的许多教程。

于 2013-06-12T21:33:55.877 回答