简单的java小程序之一键测网速

来源:互联网 发布:张子萱的淘宝店 编辑:程序博客网 时间:2024/05/16 19:18
Java代码 复制代码 收藏代码
  1. //主类
  2. import java.awt.BorderLayout;
  3. import java.awt.Color;
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6. import javax.swing.JFrame;
  7. import javax.swing.JScrollPane;
  8. import javax.swing.JTextPane;
  9. import javax.swing.text.BadLocationException;
  10. import javax.swing.text.DefaultStyledDocument;
  11. import javax.swing.text.MutableAttributeSet;
  12. import javax.swing.text.SimpleAttributeSet;
  13. import javax.swing.text.StyleConstants;
  14. public class Test {
  15. public static void main(String[] args) {
  16. try {
  17. JFrame frame = new JFrame();
  18. JTextPane text = new JTextPane();
  19. frame.getContentPane().setLayout(new BorderLayout());
  20. frame.getContentPane().add(new JScrollPane(text));
  21. frame.setTitle("网速测试");
  22. frame.setSize(800, 600);
  23. frame.setVisible(true);
  24. String[] cmd = new String[]{"cmd.exe","/c","ping www.baidu.com -t"};
  25. Process process = Runtime.getRuntime().exec( cmd);
  26. BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
  27. String info = "";
  28. DefaultStyledDocument doc = (DefaultStyledDocument)text.getStyledDocument();
  29. MutableAttributeSet attr = new SimpleAttributeSet();
  30. StyleConstants.setForeground(attr,new Color(0,102,0));
  31. while((info = br.readLine()) != null){
  32. if(!"".equals(info)){
  33. try {
  34. doc.insertString(doc.getLength(), info, attr);
  35. doc.insertString(doc.getLength(), "\r\n", null);
  36. } catch (BadLocationException e) {
  37. e.printStackTrace();
  38. }
  39. text.setCaretPosition(doc.getLength());
  40. }
  41. }
  42. } catch (Exception e) {
  43. }
  44. }
  45. }