java - 从文件中获取行号

标签 java line-numbers

如何实现一种方法来返回当前正在从文件中扫描的行的行号。我有两台扫描仪,一台用于文件 (fileScanner),另一台用于线路 (lineScanner)

这就是我所拥有的,但我不知道构造函数中是否需要行号!

public TextFileScanner(String fileName) throws FileNotFoundException
{
    this.fileScanner = new Scanner(new File(fileName));
    this.lineScanner = new Scanner(this.fileScanner.nextLine());
    this.lineNumber = 1;
}

我需要这个方法:

public int getLineNumber()
{

}

最佳答案

您可以仅使用一个 Scanner 对象来读取文件并报告行号。

这里是一个示例代码:

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

public class LineNumber {

    public static void main(String [] args) throws FileNotFoundException {

        System.out.printf("Test!\n");

        File f = new File("test.txt");
        Scanner fileScanner = new Scanner(f);

        int lineNumber = 0;
        while(fileScanner.hasNextLine()){
            System.out.println(fileScanner.nextLine());
            lineNumber++;
        }

        fileScanner.close();
        System.out.printf("%d lines\n", lineNumber);

    }
}

现在,如果您想使用面向对象的编程方法来执行此操作,那么您可以执行以下操作:

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

public class FileProcessor {

    // Mark these field as private so the object won't get tainted from outside
    private String fileName;
    private File file;

    /**
     * Instantiates an object from the FileProcessor class
     * 
     * @param fileName
     */
    public FileProcessor(String fileName) {
        this.fileName = fileName;
        this.file = new File(fileName);
    }

    public int getLineNumbers() {

        Scanner fileScanner = null;

        try {
            fileScanner = new Scanner(this.file);
        } catch (FileNotFoundException e) {
            System.out.printf("The file %s could not be found.\n",
                    this.file.getName());
        }

        int lines = 0;

        while (fileScanner.hasNextLine()) {
            lines++;
            // Go to next line in file
            fileScanner.nextLine();
        }

        fileScanner.close();

        return lines;
    }

    /**
     * Test our FileProcessor Class
     * 
     * @param args
     * @throws FileNotFoundException
     */

    public static void main(String[] args) throws FileNotFoundException {

        FileProcessor fileProcessor = new FileProcessor("text.txt");
        System.out.printf("%d lines\n", fileProcessor.getLineNumbers());
    }
}

关于java - 从文件中获取行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636157/

相关文章:

java - 如何在 Java 程序中显示带有行号的文件?

python - 调试:获取调用函数的文件名和行号?

java - BufferedReader.readline() 挂起

java - Libgdx 同时按键

java - 如何获取Java堆的内存地址?

javascript - Chrome 是否支持错误对象上的 lineNumber 属性?

java - 解码 URL,而编码字符串在双引号中

java - 如何判断 Java import 语句何时使用通配符匹配?

perl - 在 Perl 中查找文件中所有出现的字符串并打印其行号

java - 使用java在文件中查找没有行时遇到困难?