如何从java中的文件中读取单行

如何从java中的文本文件中读取单行。 知道线路完成的标准是什么。

其次

我读取文件然后读取线function并将其转换为字符串将跳过大量数据? 应该是什么问题? 这是我的代码

String data = new String(); while(infile.readLine() != null) { data = infile.readLine(); System.out.println(data); } 

更改您的代码如下

  while((data = infile.readLine()) != null) { // read and store only line System.out.println(data); } 

在您当前的代码中

  while(infile.readLine() != null) { // here you are reading one and only line data = infile.readLine(); // there is no more line to read System.out.println(data); } 

您正在读取一个额外的行,因为第一个readLine()作为while条件读取一行但它完全被使用。 while循环中的第二个readLine()读取您分配给data和打印的第二行。

因此,您需要将while条件中读取的行分配给data并打印,因为这是第一行。

 while((data = infile.readLine()) != null) { // reads the first line // data = infile.readLine(); // Not needed, as it reads the second line System.out.println(data); // print the first line } 

此外,由于您只需要阅读第一行,您根本不需要while 。 一个简单的if会这样做。

 if((data = infile.readLine()) != null) { // reads the first line System.out.println(data); // print the first line } 

使用BufferedReader和您在评论中发布的代码,您的主要现在应该是这样的。

 public static void main(String[] args) { try { FileInputStream fstream = new FileInputStream(args[0]); BufferedReader infile = new BufferedReader(new InputStreamReader( fstream)); String data = new String(); while ((data = infile.readLine()) != null) { // use if for reading just 1 line System.out.println(data); } } catch (IOException e) { // Error } } 

第一件事: readLine()仅返回String值,因此它不会转换为String。

第二件事:在你的while循环中,你读取第一行并检查第一行的内容是否为空。 但是当data = infile.readLine(); 执行时,它将从文件中获取第二行并将其打印到控制台。

将while循环更改为:

 while((data = infile.readLine()) != null){ System.out.println(data); } 

如果你使用toString()方法,它会在尝试使用带有从infile读取的null内容的toString方法时抛出NPE。