首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从文件中获取行号

从文件中获取行号
EN

Stack Overflow用户
提问于 2013-07-14 11:02:55
回答 1查看 18.3K关注 0票数 2

我如何实现一个方法来返回当前从文件扫描的行号。我有两个扫描器,一个用于文件(fileScanner),另一个用于行(lineScanner)

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

代码语言:javascript
复制
public TextFileScanner(String fileName) throws FileNotFoundException
{
    this.fileScanner = new Scanner(new File(fileName));
    this.lineScanner = new Scanner(this.fileScanner.nextLine());
    this.lineNumber = 1;
}

我需要这个方法:

代码语言:javascript
复制
public int getLineNumber()
{

}
EN

回答 1

Stack Overflow用户

发布于 2013-07-14 11:50:38

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

下面是一个示例代码:

代码语言:javascript
复制
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);

    }
}

现在,如果你想使用面向对象的编程方法来实现这一点,那么你可以这样做:

代码语言:javascript
复制
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());
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17636157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档