1

I have a file with say 20 lines. I need to read first 3 lines, process it and write it to another file. Then give a delay of 62 seconds, read the next 3 lines and so on till the nth line. How do I go about it?. I was successful in writing first 3 lines, but confused where to put the loop for another iteration.

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();
        }
    }

}

Scitech
  • 513
  • 1
  • 5
  • 16
  • http://stackoverflow.com/questions/3342651/how-can-i-delay-a-java-program-for-a-few-seconds – Siddharth Kumar Oct 09 '15 at 06:18
  • I have no problem with the time delay. Looping is the question. After the delay it should return to some loop and process next 3 lines. Where can I include that loop and how. – Scitech Oct 09 '15 at 06:20

1 Answers1

2

try this. So it will sleep every third attempt.

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

    // process the data which you have read.

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

}
Janath
  • 137
  • 9