[英]Go to next line in a file with BufferedReader
我正在尝试从文件中读取行。 为此,我使用以下代码:
try {
String line;
try (InputStream fis = new FileInputStream("AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
FactGeneration.getFacts();
while ((line = br.readLine()) != null) {
br.readLine();
function1(line);
但是,这不会移动到文件中的下一行。 谢谢!
编辑:为清楚起见,我正在制作一个 twitter 机器人。 整个 function 如下所示: FactGeneration.getFacts() 将新行附加到位于 /AbsoluteFilePath 的文件中
private static void tweetLines() {
String tweet;
int count = 0;
while (count < 10) {
try {
try (InputStream fis = new FileInputStream(
"/AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
FactGeneration.getFacts();
while ((tweet = br.readLine()) != null) {
sendTweet(tweet);
try {
int sleepTime = 18000;
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
count += 1;
}
}
编辑:
以下是工作代码:
while (count < numTweets) {
try {
try (InputStream fis = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr)) {
//Calls static method GetFacts from the FactGeneration class.
FactGeneration.getFacts();
tweet = br.readLine();
while (tweet != null) {
//sendTweet accesses the TwitterAPI and posts the tweet.
sendTweet(tweet);
System.out.println("tweeting:" + tweet);
try {
//Pauses the thread for the given amount of time.
int sleepTime = 18000; //in milliseconds.
System.out.printf("Sleeping for %d seconds", sleepTime / 1000);
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
e.printStackTrace();
}
//moves to the next line in the file.
tweet = br.readLine();
}
}
}
catch (IOException e) {
e.printStackTrace();
}
count += 1;
if (count == numTweets) {
System.out.println("Tweet limit reached");
}
}
readLine
实际上读取了一行,它在while
循环的条件内执行,所以不要在循环内读取第二次
String line;
try (InputStream fis = new FileInputStream("AbsoluteFilePath");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("Cp1252"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
// do whatever with line
}
}
while
条件有 2 个步骤,这允许最后读取null
并停止循环
line
line
不是 null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.