如何根据时间间隔从arraylist中检索值?

时间:2014-04-29 04:55:23

标签: java arraylist

您好我正在尝试获取一个URL,当我获取该URL时,我得到一个字符串。我保留在arraylist中的字符串。现在我要打印arraylist值。条件是每x秒只能打印15个值。

这是我的代码:

public class CommoditywiseGetUrl {

    public static void main(String args[]) {
        URL url;
        try {
            // get URL content

            String a = "http://122.160.81.37:8080/mandic/commoditywise?c=paddy";
            url = new URL(a);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            ArrayList<String> list1 = new ArrayList<String>();
            ArrayList<String> list2 = new ArrayList<String>();

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

                String s = inputLine.replace("|", "\n");

                s = s.replace("~", " ");
                //System.out.println(s);
                StringTokenizer str = new StringTokenizer(s);
                while (str.hasMoreTokens()) {
                    String mandi = str.nextElement().toString();

                    String price = str.nextElement().toString();


                    list1.add(mandi);
                    list2.add(price);
                }
            }
            String item1 = null;
            for (int i = 0; i < list1.size(); i++) {
                item1 = list1.get(i);
                System.out.println("mandi" + item1);
            }
            for (int i = 0; i < list2.size(); i++) {
                String item2 = list2.get(i);
                System.out.println("Price" + item2);
            }

            br.close();

            //System.out.println(sb);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

如何达到我想要的输出?

感谢。

1 个答案:

答案 0 :(得分:0)

您的列表填充逻辑与列表元素的计划打印无关。所以最好不要混合它们。我建议你使用java util Timer来安排细粒度控制的打印。 我无法运行您的代码,但这里有一个关于如何使用计时器的想法:

        Timer timer = new Timer();
        timer.schedule(new RunMeTask(), 1000,60000); // executes every 60 secs with 1 sec delay

RumeMetask可能看起来像

 public static class RunMeTask extends TimerTask
{

        @Override
        public void run() {
              String item1 = null;
                for (int i = count; i < 16; i++) {
                    item1 = list1.get(i);
                    System.out.println("mandi" + item1);
                }
                for (int i = count; i < 16; i++) {
                    String item2 = list2.get(i);
                    System.out.println("Price" + item2);
                }

        }

     }