如何在Java中阅读textfile的nextline?

时间:2017-03-31 16:12:12

标签: java file line file-handling

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 个答案:

答案 0 :(得分:1)

您可以逐行阅读文件:

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

答案 1 :(得分: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
}
  }
}

将print语句放在循环