如何实现一种方法来从文件中返回当前正在扫描的行的行号。我有两个扫描仪,一个用于文件(fileScanner),另一个用于行(lineScanner)
这就是我所拥有的,但我不知道我是否需要构造函数中的linenumber!
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()
{
}
答案 0 :(得分:3)
您只能使用一个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());
}
}
答案 1 :(得分:0)
打印当前行号:
System.out.println("行号为" + new Exception()。getStackTrace()[0] .getLineNumber());
示例:
public class LineNumberTest {
public static void main(String []args){
System.out.println("The line number is " + new Exception().getStackTrace()[0].getLineNumber());
}
}