如何确定正在读取的文件的哪一行特定行

时间:2013-10-30 05:32:15

标签: java file line

Scanner scans = new Scanner(System.in);
  System.out.print("Enter filename: ");
  String thisfile = scans.nextLine();
  File thatfile = new File(thisfile);
  FileInputStream fileInput = new FileInputStream(thatfile);
  int i;
  while ((i = fileInput.read()) != -1) {
     char a = (char) i;
   }

我正在使用上面的代码获取文件(java程序)并按每个字符搜索文件。如何确定特定字符所在的行。例如,如果这是程序:

public class HelloWorld {
public static void main(String[] args) {
    System.out.println("Hello, World");
}
}

如果我在系统的S上,我怎样才能使用代码正确地确定它在第3行?对不起,如果我不清楚,但很难解释。

1 个答案:

答案 0 :(得分:1)

如何增强你的循环

char newline_character = <whatever is appropriate for your file>;
int line = 0;
while ((i = fileInput.read()) != -1) {
   char a = (char) i;
   if (a==newline_character) { ++line; }
}
相关问题