将几行写入延迟文件

时间:2015-10-09 06:11:20

标签: java iteration writer

我有一个说20行的文件。我需要读取前3行,处理它并将其写入另一个文件。然后延迟62秒,读取接下来的3行,依此类推,直到第n行。我怎么去呢?我成功地写了前3行,但是把这个循环放到另一个迭代的地方很困惑。

FileInputStream fis = new FileInputStream("C:\\Users\\Rao\\Desktop\\test.txt");
br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

            String sCurrentLine;
            int counter = 0;
            while ((sCurrentLine = br.readLine()) != null) {
                if (counter < 3) {
              URL oracle = new URL("http://ip-api.com/json/"+sCurrentLine+"?"+"fields=isp");
              BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                          String baby= (sCurrentLine+ "\t"+ inputLine); 

                 try { 
                        FileWriter writer = new FileWriter("C:\\Users\\Rao\\Desktop\\output.txt", true);
                        writer.write(baby);
                        writer.write("\r\n");   // write new line
                        writer.close();

                     } catch (IOException e) {
                        e.printStackTrace();
                        }
                } in.close();
             }

            counter++; }
            TimeUnit.SECONDS.sleep(62); }
        finally {
            if (br != null) br.close();
        }
    }

}

1 个答案:

答案 0 :(得分:2)

试试这个。所以每三次尝试都会睡一觉。

while ((sCurrentLine = br.readLine()) != null) {

    // process the data which you have read.

    if ((counter % 3) == 0 ) {
       TimeUnit.SECONDS.sleep(62); 
    }

}