【问题标题】:How to read nextline of textfile in Java?如何在 Java 中读取文本文件的下一行?
【发布时间】:2017-08-25 23:51:31
【问题描述】:
import java.io.*;
import java.util.*;
public class stringstore
{
    public static void main(String[] args)
    {
        File file = new File("C:\\a.txt");
        try
        {
            String strIP="";
            Scanner sc = new Scanner(file);
            while(sc.hasNext())
            {
                String line = sc.nextLine();
                String str[] = line.split(", ");
                strIP = str[0];
            }
            System.out.println(strIP);
        }
        catch(IOException e)
        {
        // work with the errors here
        }
    }
}

如何从文本文件中读取下一行并显示它。

【问题讨论】:

  • re "Urgent/ASAP"(来源:link):“你最好不要在你的帖子中说明这一点。即使对你来说很紧急,也要意识到这并不紧急我们。这里的许多人对此感到不满,因为这对他们来说意味着 a) 发帖人认为他的帖子比其他人的帖子更重要(并不是因为这里的所有问题都同样重要), b) 发帖人想对那些利用自己的空闲时间来这里提供帮助的志愿者施加压力。”
  • 您自己的代码已经展示了如何使用 Scanner 的 nextLine 方法。而且您已经知道如何使用 println。那么混乱在哪里呢?
  • BTW hasNext() 正在测试文本中是否有下一个标记(单词)。如果在最后一个单词之后会有两个空行 hasNext() 将返回 false。请改用hasNextLine()

标签: java file line file-handling


【解决方案1】:

您的代码中只有轻微的错误。 试试这个。

import java.io.*;
   import java.util.*;
   public class stringstore
 {
   public static void main(String[] args)
{
    File file = new File("C:\\a.txt");
 try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
    String line = sc.nextLine();
    String str[] = line.split(", ");
    strIP = str[0];
System.out.println(strIP);
}

}
catch(IOException e)
{
  // work with the errors here
}
  }
}

将打印语句放在循环中

【讨论】:

    【解决方案2】:

    你可以逐行读取文件:

            BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-04
      • 2019-02-03
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      相关资源
      最近更新 更多