如何在Java中读取文本文件的下一行?
如何从文本文件中读取下一行并显示它。您可以逐行读取文件:如何在Java中读取文本文件的下一行?,java,file,line,file-handling,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=""; S
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
}
}
}
你的代码中只有一点小错误。 试试这个
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
将打印声明放在循环中re“emergency/ASAP”(来源:):“你最好不要在你的帖子中说明这一点。即使这对你来说很紧急,也要意识到这对我们来说并不紧急。这里的许多人对此表示不满,因为这意味着a)海报认为他的帖子比其他人的帖子更重要(并不是因为这里的所有问题都同样重要)和b)海报想要给那些在自己空闲时间来这里帮忙的志愿者施加压力。“你自己的代码已经展示了如何使用Scanner的nextLine方法。你已经知道如何使用println了。那么混淆在哪里呢?顺便说一句,hasNext()正在测试文本中是否有下一个标记(单词)。如果在最后一个单词之后有两个空行
hasNext()
将返回false
。改用hasNextLine()
。
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
}
}
}