【问题标题】:Capturing Specific Parts of InputStreamReader in Java在 Java 中捕获 InputStreamReader 的特定部分
【发布时间】:2013-04-25 11:10:46
【问题描述】:

所以我正在开发一个小 GUI,它从命令行 ping 从 IP 列表中选择的 IP。我有这个工作并通过 getInputStream 返回输出。

这是我运行 ping 的代码:

    String pingResult = "";
    try {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec("ping " + IPAddressList.getSelectedValue());
        try (BufferedReader in = new BufferedReader(new InputStreamReader
                (p.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                pingResult += inputLine;
            }
        }

    }//try
    catch (IOException e) {
        System.out.println(e);
    }

我现在需要做的是来自 IP 列表(存储在带有 DefaultModel 名称机器的 Jlist 中),我需要不断地允许 ping 列表的 IP 并更新列表(我对如何进行更新有了一个想法)。

我不知道如何使用上面的一些代码来启动这个循环并保持它运行。此外,在它运行时,我需要确保 GUI 可以执行其他操作,例如:从列表中删除 IP、将 IP 添加到列表、ping 单个 IP 等。

感谢您的帮助。

【问题讨论】:

    标签: java loops command-line-arguments ping interrupt


    【解决方案1】:

    您需要在后台线程中启动 ping。使用SwingWorker 可能是实现这一点的最简单方法。您可以很容易地向它传递一个 IP 地址列表,它将在后台运行 ping 每个地址,然后将中间结果传递回您的 GUI。 SwingWorker 类的优点之一是它确保结果的处理发生在 Swing 的主事件分派线程中,因此您不需要做任何额外的事情来处理它。

    Javadoc 很好地概述了它的用法:

    http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html

    下面是一个粗略的起点。然后您将实例化它并调用其execute() 方法来启动后台进程。

    class PingWorker extends SwingWorker<Void, PingResult> {
        private List<IpAddress> addresses;
    
        public PingWorker(List<IpAddress> addresses) {
            this.addresses = addresses;
        }
    
        @Override
        protected Void doInBackground() throws Exception {
            for (IpAddress address : addresses) {
                // run ping code and build result
                publish(new PingResult(address /* other result params here */));
            }
    
            // no need to return anything as we are processing the intermediate results
            return null;
        }
    
        @Override
        protected void done() {
            // pings are complete, update GUI to reflect this
        }
    
         @Override
         protected void process(List<PingResult> results) {
             for (PingResult result : results) {
                 // update GUI with the result of the ping such as your table model
             }
         }
    }
    

    【讨论】:

    • 这看起来很棒 Ed,我明天会尝试完成编码。非常感谢!
    【解决方案2】:

    您可以在不同的线程上启动 try 循环中的所有内容,以便它独立运行,然后您可以在它继续运行的同时做任何您想做的事情(添加/删除 IP)。

    按照本教程进行操作,您将找到大部分所需内容: Java Tutorials: Concurrency

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      相关资源
      最近更新 更多