fileReader和扫描仪

时间:2013-06-12 20:38:40

标签: java.util.scanner filereader

我不明白如何从下面的.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);
    }

1 个答案:

答案 0 :(得分:1)

以下是使用扫描仪的readFile示例。因此,您应该导入三个重要的包:

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

之后,您将创建文件对象以及文件的name参数。然后,创建扫描仪对象。最后,您可以使用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();
        }

    }

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