簡體   English   中英

Go 到帶有 BufferedReader 的文件中的下一行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM