【问题标题】:fileReader and scanner文件阅读器和扫描仪
【发布时间】:2013-06-12 20:38:39
【问题描述】:

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

【问题讨论】:

  • 真的吗?你甚至保留了练习号
  • 你的冒险精神在哪里? :) 查看Scanner 类的文档(网络|| 教科书),即使键入带有句点的变量,如fileReader.,也应该打开IntelliSense 并给你一些想法。 (我不会去-1,因为你刚刚开始stackoverflow)

标签: java.util.scanner filereader


【解决方案1】:

以下是使用 Scanner 读取文件的示例。所以,你应该导入三个重要的包:

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

    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 2013-12-04
    相关资源
    最近更新 更多