Javafx 获取 Ping 结果

标签 java user-interface javafx ping

我已经编写了一个类来 ping 我提供的 IP 地址,但它不会返回任何内容。 我尝试添加一些标记以查看哪里出了问题,但即使那样也没有用...... 我有一个 gui 界面,我使用标签写出我的数据(以前使用字符串的格式相同),这是代码。有些行我想要或不想要,因此是“相关”整数,您可以忽略它。这应该在 ubuntu 13.10 上运行。

public static ArrayList<String> PingIpAddr(String string) throws IOException{
        String s = new String();
        int relevant =0;
        ArrayList<String> List = new ArrayList<String>();
        List.add("it happens \n");
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(new ProcessBuilder(string).start().getInputStream()));
        while ((s = stdInput.readLine()) != null){
             List.add("does this happen? \n");
            relevant++;
            if( (relevant == 2) || (relevant == 3) || (relevant == 4) || (relevant == 5) || (relevant == 6) || (relevant == 9) ){List.add(s + "\n");
            List.add("or this? \n");}}  //end of while
        List.add("This must happen! \n");
        return List;}   //end of Ping

如果这行得通,这里是实现它的地方:

    String test;
    test = PingIp.testPingIpAddr("ping -c 5 4.2.2.2").toString();
    TeltonikaPing.setWrapText(true);
    TeltonikaPing.setText(test);

奇怪的是它没有返回一行。也许我只是缺少一些非常基本的东西?:/

最佳答案

  1. 主要问题是 ping 在大多数情况下有延迟,请尝试使用 stdInput.ready()。

  2. 我可能会将其传递给 ProcessBuilder:new ProcessBuilder("myCommand", "myArg1", "myArg2");从参数中拆分出命令 ping。

如 - http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

希望对您有所帮助(:

编辑——(这在下面起作用)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Pinger
{
    public static List<String> PingIpAddr(String ip) throws IOException
    {
        ProcessBuilder pb = new ProcessBuilder("ping", ip);
        //ProcessBuilder pb = new ProcessBuilder("ping", "-c 5", ip);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(pb.start().getInputStream()));        

        while (!stdInput.ready())
        {
            // custom timeout handling
        }

        String line;
        ArrayList<String> output = new ArrayList<>();

        while ((line = stdInput.readLine()) != null)
        {
            output.add(line);
        }

        return output;
    }

    public static void main(String[] args) throws IOException
    {
        List<String> lines = Pinger.PingIpAddr("127.0.0.1");

        for (String line : lines)
        {
            System.out.println(line);
        }
    }
}

关于Javafx 获取 Ping 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24994261/

相关文章:

java - 不带括号的通用静态方法,例如在 JavaFX 8 中

java - 如何在 Java 中刷新 Window 类的图形

c - 如何为基于文本的程序创建 GUI?

java - 为什么 JPanel 会自动重绘?

java - 更改 SWT 中嵌套复合 Material 顶边之间的间距

java - 如何让我的 Java 编译器在 Ubuntu Linux 上识别旧版本的 OpenJFX for Java 8?

java - 使用 Spring Boot 加载本地库

java - 布局中的 Eclipse ADT Open 声明不再默认

java - 加载 XML 配置文件时出现 Log4j2 错误

javafx - 如何在 JavaFX 中将 FontAwesome 升级到版本 5