JAVA编写的IP地址动态切换软件

这个是1.0版,自己觉得刚学习Java只有多实践才能有提高,可供大家一同学习分享。

一共有4个类  MainApplet.java   ConfigFile.java   ExecCmd.java  SystemVars.java

下面是源代码:

1. MainApplet.java类

package com.zhangzhen.cmd;

 

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class MainApplet extends JApplet
{
 
   private JButton jbtSave = new JButton("Save");
   
   
   private JButton jbtDelete = new JButton("Delete");
   
   private JButton jbtOK = new JButton("OK");
   
   private JButton jbtAuto = new JButton("Auto");
   
   private JButton jbtExit = new JButton("Exit");
   
   
   private JLabel jlblIPAddress = new JLabel("IP地址:");
   
   private JTextField jtfIPAddress = new JTextField();
   
   private JLabel jlblSubnetMask = new JLabel("子网掩码: ");
   
   private JTextField jtfSubnetMask = new JTextField();
   
   private JLabel jlblGateway = new JLabel("默认网关:");
   
   private JTextField jtfGateway = new JTextField();
   
   private JLabel jlblDNSfirst = new JLabel("首选DNS服务器:");
   
   private JTextField jtfDNSfirst = new JTextField();
   
   private JLabel jlblDNSremark = new JLabel("备用DNS服务器:");
 
   private JTextField jtfDNSremark = new JTextField();
   
   
   private JLabel jlblConfigFileName = new JLabel("配置项名称:");
   
   private JTextField jtfConfgFileName = new JTextField();
   
   
   private JList jlConfigItem = new JList();
   
   
   DefaultListModel dlmConfigItem = new DefaultListModel();
   
   
   SystemVars configInfo = new SystemVars();
   
   
   
    public void init()
    {
     super.setSize(1000,500);
        setLayout(new BorderLayout());
       
        //添加控制按钮面板
     JPanel jpControl = new JPanel();
        jpControl.setLayout(new FlowLayout());
        // 设置按钮属性
        jbtSave.setMnemonic(KeyEvent.VK_S);
        jbtDelete.setMnemonic(KeyEvent.VK_DELETE);
        jbtOK.setMnemonic(KeyEvent.VK_O);
        jbtAuto.setMnemonic(KeyEvent.VK_A);
        jbtExit.setMnemonic(KeyEvent.VK_E);
        //添加控制按钮
        jpControl.add(jbtSave);
        jpControl.add(jbtDelete);
        jpControl.add(jbtOK);
        jpControl.add(jbtAuto);
        jpControl.add(jbtExit);
       
        add(jpControl,BorderLayout.SOUTH);
       
        //添加输入配置信息面板
        JPanel jpEnterConfigInfo = new JPanel();
        jpEnterConfigInfo.setLayout(new GridLayout(6,2,0,40));
       
        jpEnterConfigInfo.add(this.jlblIPAddress);
        jpEnterConfigInfo.add(this.jtfIPAddress);
        jpEnterConfigInfo.add(this.jlblSubnetMask);
        jpEnterConfigInfo.add(this.jtfSubnetMask);
        jpEnterConfigInfo.add(this.jlblGateway);
        jpEnterConfigInfo.add(this.jtfGateway);
        jpEnterConfigInfo.add(this.jlblDNSfirst);
        jpEnterConfigInfo.add(this.jtfDNSfirst);
        jpEnterConfigInfo.add(this.jlblDNSremark);
        jpEnterConfigInfo.add(this.jtfDNSremark);
       
        jpEnterConfigInfo.add(this.jlblConfigFileName);
        jpEnterConfigInfo.add(this.jtfConfgFileName);
       
        add(jpEnterConfigInfo,BorderLayout.EAST);
       
        //添加配置项列表框面板
        JPanel jpConfigItem = new JPanel();
        jpConfigItem.setLayout(new BorderLayout());
       
        //设置列表框属性
        jlConfigItem.setSelectionBackground(Color.gray);
        jlConfigItem.setSelectionForeground(Color.red);
        jlConfigItem.setVisibleRowCount(10);
        jlConfigItem.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
       
        jlConfigItem.setFixedCellHeight(30);
        jlConfigItem.setFixedCellWidth(200);
       
        jlConfigItem.setVisible(true);
       
       
       
       
        //添加配置项列表框
        jpConfigItem.add(jlConfigItem,BorderLayout.CENTER);
       
        add(new JScrollPane(jlConfigItem),BorderLayout.WEST);
       
       
       
        File configPath = new File("D:\\IP_CONFIG\");
        configPath.mkdir();
       
       
        this.jbtSave.addActionListener(new ActionListener()
        {
         public void actionPerformed(ActionEvent e)
         {
          if(MainApplet.this.jtfConfgFileName.getText().isEmpty() ||
             MainApplet.this.jtfDNSfirst.getText().isEmpty() ||
             MainApplet.this.jtfDNSremark.getText().isEmpty() ||
             MainApplet.this.jtfGateway.getText().isEmpty() ||
             MainApplet.this.jtfIPAddress.getText().isEmpty() ||
             MainApplet.this.jtfSubnetMask.getText().isEmpty()  )
          {
           //添加配置信息为空异常代码
           System.out.println("+------>请填入配置信息后再点保存按钮!");
          }
          else
          {
           
           configInfo.setIp_address(MainApplet.this.jtfIPAddress.getText());
           configInfo.setMask(MainApplet.this.jtfSubnetMask.getText());
           configInfo.setGateway(MainApplet.this.jtfGateway.getText());
           configInfo.setDns_first(MainApplet.this.jtfDNSfirst.getText());
           configInfo.setDns_remark(MainApplet.this.jtfDNSremark.getText());
           configInfo.setNetwork_name("\u672C\u5730\u8FDE\u63A5");
           configInfo.setFile_url("D:\\IP_CONFIG\");
           configInfo.setWeb_count("5");
           configInfo.setWeb_url("http://www.baidu.com/");
           configInfo.setGwmetric("1");
           configInfo.setConfigFileName(MainApplet.this.jtfConfgFileName.getText());
      
           //生成IP配置文件
           
           ConfigFile.WriteConfigFile(configInfo);
           
           //在配置项列表框中添加所保存的配置项名
           showConfigFileNameToList();
          }
         }
        });
       
       
        this.jbtOK.addActionListener(new ActionListener()
        {
         public void actionPerformed(ActionEvent e)
         {
          //选择配置项后才能修改IP地址信息
          if(jlConfigItem.isSelectionEmpty())
          {
           //添加为选择配置项提示信息代码
           System.out.println("+------->没有选择配置项,请选择一个配置项后再点OK");
          }
          else
          {
           //读取配置文件
           configInfo = ConfigFile.ReadConfigFile((String)jlConfigItem.getSelectedValue());
           //创建p文件
           ConfigFile.createPFile(configInfo);
           
           //修改配置信息
           ExecCmd.exec(configInfo);
          }
         }
        });
       
    }//end init()
   
   
   
   
   
    public void start()
    {
     
     showConfigFileNameToList();
     
     
        this.jlConfigItem.addListSelectionListener(new ListSelectionListener()
        {
         public void valueChanged(ListSelectionEvent e)
         {
          if(jlConfigItem.isSelectionEmpty())
          {
           //添加为选择配置项提示信息代码
           System.out.println("+------->没有选择配置项,请选择一个配置项");
          }
          else
          {
           //读取配置文件
           configInfo = ConfigFile.ReadConfigFile((String)jlConfigItem.getSelectedValue());
           
           //显示所选配置信息
           MainApplet.this.jtfIPAddress.setText(configInfo.getIp_address());
           MainApplet.this.jtfSubnetMask.setText(configInfo.getMask());
           MainApplet.this.jtfGateway.setText(configInfo.getGateway());
           MainApplet.this.jtfDNSfirst.setText(configInfo.getDns_first());
           MainApplet.this.jtfDNSremark.setText(configInfo.getDns_remark());
           MainApplet.this.jtfConfgFileName.setText(configInfo.getConfigFileName());
          }
         }
        });
       
       
        this.jbtDelete.addActionListener(new ActionListener()
        {
         public void actionPerformed(ActionEvent e)
         {
          if(jlConfigItem.isSelectionEmpty())
          {
           //添加为选择配置项提示信息代码
           System.out.println("+------->没有选择配置项,请选择一个配置项删除");
          }
          else
          {
           String filename = (String)jlConfigItem.getSelectedValue();
           //删除所选配置文件
           ConfigFile.delete("D:\\IP_CONFIG\"+filename+".properties");
           //删除对应P文件
           ConfigFile.delete("D:\\IP_CONFIG\"+filename+".txt");
           //更新列表框
           showConfigFileNameToList();
           //清除文本域
           jtfIPAddress.setText(null);
           jtfSubnetMask.setText(null);
           jtfGateway.setText(null);
           jtfDNSfirst.setText(null);
           jtfDNSremark.setText(null);
              jtfConfgFileName.setText(null);
          }
         }
        });
       
       
        this.jbtExit.addActionListener(new ActionListener()
        {
         public void actionPerformed(ActionEvent e)
         {
          System.exit(1);
         }
        });
       
       
        this.jbtAuto.addActionListener(new ActionListener()
        {
         public void actionPerformed(ActionEvent e)
         {
          ExecCmd.dhcp();
         }
        });
    }
   
   
    public void showConfigFileNameToList()
    {
     //清除原来列表框内容
     this.dlmConfigItem.clear();
     this.jlConfigItem.setModel(dlmConfigItem);
     //获得配置文件名
     ArrayList<String> al = ConfigFile.getConfigFileName();
     //显示到列表框中
     for(int i=0 ; i < al.size(); i++)
     {
         this.dlmConfigItem.addElement((String)al.get(i));
     }
     this.jlConfigItem.setModel(dlmConfigItem);
    }


}

 

2.ConfigFile.java类

 

package com.zhangzhen.cmd;

 


import java.io.*;
import java.util.ArrayList;
import java.util.Properties;

public class ConfigFile
{
 
 public static void WriteConfigFile(SystemVars config)
 {
  //创建配置文件目录
  ConfigFile.mkdir(config.getFile_url());
  
  java.util.Properties p = new java.util.Properties();
  
  
  String comments = new String();
  try
  {
   File f  = new File(config.getFile_url()+config.getConfigFileName()+".properties");
   f.createNewFile();


   PrintWriter pw = new PrintWriter(new FileWriter(f));
  
      p.setProperty("FILE_URL", config.getFile_url());
      p.setProperty("NETWORK_NAME", config.getNetwork_name());
      p.setProperty("IP_ADDRESS", config.getIp_address());
      p.setProperty("MASK",config.getMask());
      p.setProperty("GATEWAY",config.getGateway());
      p.setProperty("GWMETRIC",config.getGwmetric());
      p.setProperty("DNS_FIRST",config.getDns_first());
      p.setProperty("DNS_REMARK",config.getDns_remark());
      p.setProperty("WEB_COUNT", config.getWeb_count());
      p.setProperty("WEB_URL",config.getWeb_url());
      p.setProperty("FILE_NAME",config.getConfigFileName());
      p.store(pw, comments);
  }
  catch(IOException e)
  {
   System.out.println("+----->写配置文件异常!");
   e.printStackTrace();
  }
 }
 
 
 
 public static SystemVars ReadConfigFile(String fileName)
 {
  String fileURL = "D:\\IP_CONFIG\"+fileName+".properties";
  SystemVars config = new SystemVars();
  
  Properties p = new Properties();
  
  try
  {
   FileReader fr = new FileReader(fileURL);
   p.load(fr);
   config.setConfigFileName(p.getProperty("FILE_NAME"));
   config.setFile_url(p.getProperty("FILE_URL"));
   config.setNetwork_name(p.getProperty("NETWORK_NAME"));
   config.setIp_address(p.getProperty("IP_ADDRESS"));
   config.setMask(p.getProperty("MASK"));
   config.setGateway(p.getProperty("GATEWAY"));
   config.setGwmetric(p.getProperty("GWMETRIC"));
   config.setDns_first(p.getProperty("DNS_FIRST"));
   config.setDns_remark(p.getProperty("DNS_REMARK"));
   config.setNetwork_name(p.getProperty("NETWORK_NAME"));
   config.setWeb_count(p.getProperty("WEB_COUNT"));
   config.setWeb_url(p.getProperty("WEB_URL"));
   
   //FileReader必须和文件断开
   fr.close();
  }
  catch (FileNotFoundException e)
  {
   e.printStackTrace();
  }
  catch(IOException ioe)
  {
   ioe.printStackTrace();
  }
  return config;
 }
 
 
 public static void createPFile(SystemVars config)
 {
  //生成新的目录
  ConfigFile.mkdir(config.getFile_url());
  
  String [] str = new String[7];
  //生成P处理命令
  str[0]="pushd interface ip ";
  str[1]="set address name="+config.getNetwork_name()+" source=static addr="+config.getIp_address()+" mask="+config.getMask();
  str[2]="set address name="+config.getNetwork_name()+" gateway="+config.getGateway()+" gwmetric="+config.getGwmetric();
  str[3]="set dns name="+config.getNetwork_name()+" source=static addr="+config.getDns_first();
  str[4]="add dns name="+config.getNetwork_name()+" addr="+config.getDns_remark();
  str[5]="set wins name="+config.getNetwork_name()+" source=static addr=none ";
  str[6]="popd ";
  //生成P文件
  ConfigFile.createFile(config.getFile_url()+config.getConfigFileName()+".txt" , str );
 }
 
   
 public static void mkdir(String path)
 {
  String mkdirName = path;
  try
  {
   File dirFile = new File(mkdirName);
   boolean bFile = dirFile.exists();
   if(!bFile)//如果文件目录不存在
   {
    bFile = dirFile.mkdir();
    if(!bFile)//如果文件目录创建失败
    {
        //添加文件目录创建失败弹出信息代码
     
     System.exit(1);
    }
   }
  } catch(Exception err)
  {
   System.err.println("+-------->文件夹创建发生异常");
   System.out.println("+-------->"+err.getMessage());
  }
 }
 
 
 public static void createFile(String fileUrl,String []content)
 {
  PrintWriter pw;
  try
  {
   pw = new PrintWriter(new FileWriter(fileUrl));
   
   for (int i = 0; i < content.length; i++)
   {
    pw.println(content[i]);
   }
   //PrintWriter与文件断开
   pw.close();
  }
  catch(IOException e)
  {
   System.out.println("+-------->创建文件失败!!!");
   System.out.println("+-------->"+e.getMessage());
  }
 }
 
 
 public static ArrayList<String> getConfigFileName()
 {
  ArrayList<String> al = new ArrayList<String>(20);
  String path = "D:\\IP_CONFIG\";
  File f = new File(path);
  
  String [] fileName=new String[100];
  
  
  if(f.exists())//如果配置文件路径存在
  {
   fileName = f.list(new FilenameFilter()
   {
    public boolean accept(File dir,String name)
    {
     if(name.endsWith(".properties"))
     {
      return true;
     }
     else
     {
      return false;
     }
    }
   });
  }
  else
  {
   //添加配置文件目录不存在异常
   System.out.println("+--------->配置文件目录不存在!");
  }
  for(int i = 0 ; i < fileName.length ; i++)
  {
   fileName[i] = fileName[i].substring( 0 , fileName[i].indexOf('.') );
   al.add(fileName[i]);
  }
  return al;
 }
 
 
 
 public static boolean delete(String fileName)
 {
  File file = new File(fileName);
  if(!file.exists())
  {
   return false;
  }
  else if(file.isFile())
  {
   return deleteFile(fileName);
  }
  else
  {
   return deleteDirectory(fileName);
  }
 }
 
 
 public static boolean deleteFile(String fileName)
 {
  File file = new File(fileName);
  if(file.isFile()&& file.exists())
  {
   file.delete();
   System.out.println("+-------->删除单个文件" + fileName + "成功!");
   return true;
  }
  else
  {
   System.out.println("+-------->删除单个文件" + fileName + "失败!");
   return false;
  }
 }
 
 
 public static boolean deleteDirectory(String dir)
 {
  // 如果dir不以文件分隔符结尾,自动添加文件分隔符
  if (!dir.endsWith(File.separator))
  {
   dir = dir + File.separator;
  }
  File dirFile = new File(dir);
  // 如果dir对应的文件不存在,或者不是一个目录,则退出
  if (!dirFile.exists() || !dirFile.isDirectory())
  {
   System.out.println("+-------->删除目录失败" + dir + "目录不存在!");
   return false;
  }
  boolean flag = true;
  // 删除文件夹下的所有文件(包括子目录)
  File[] files = dirFile.listFiles();
  for (int i = 0; i < files.length; i++)
  {
   // 删除子文件
   if (files[i].isFile())
   {
    flag = deleteFile(files[i].getAbsolutePath());
    if (!flag)
    {
     break;
    }
   }
   // 删除子目录
   else
   {
    flag = deleteDirectory(files[i].getAbsolutePath());
    if (!flag)
    {
     break;
    }
   }
  }

   if (!flag)
  {
        System.out.println("+-------->删除目录失败");
       return false;
  }

// 删除当前目录
  if (dirFile.delete())
  {
   System.out.println("+-------->删除目录" + dir + "成功!");
   return true;
  }
  else
  {
   System.out.println("+-------->删除目录" + dir + "失败!");
   return false;
  }
 }

}
 

 

 

 

3.SystemVars.java类

 

 

package com.zhangzhen.cmd;

public class SystemVars
{
 
 private String file_url;
 
 private String network_name;
 
 private String ip_address;
 
 private String mask;
 
 private String gateway;
 
 private String gwmetric;
 
 private String dns_first;
 
 private String dns_remark;
 
 private String web_count;
 
 private String web_url;
 
 
 
 
 private String configFileName;
 
 
 public String getNetwork_name()
 {
  return network_name;
 }
 public void setNetwork_name(String networkName)
 {
  network_name = networkName;
 }
 public String getIp_address()
 {
  return ip_address;
 }
 public void setIp_address(String ipAddress)
 {
  ip_address = ipAddress;
 }
 public String getMask()
 {
  return mask;
 }
 public void setMask(String mask)
 {
  this.mask = mask;
 }
 public String getGateway()
 {
  return gateway;
 }
 public void setGateway(String gateway)
 {
  this.gateway = gateway;
 }
 public String getGwmetric()
 {
  return gwmetric;
 }
 public void setGwmetric(String gwmetric)
 {
  this.gwmetric = gwmetric;
 }
 public String getDns_first()
 {
  return dns_first;
 }
 public void setDns_first(String dnsFirst)
 {
  dns_first = dnsFirst;
 }
 public String getDns_remark()
 {
  return dns_remark;
 }
 public void setDns_remark(String dnsRemark)
 {
  dns_remark = dnsRemark;
 }
 public String getFile_url()
 {
  return file_url;
 }
 public void setFile_url(String fileUrl)
 {
  file_url = fileUrl;
 }
 public String getWeb_count()
 {
  return web_count;
 }
 public void setWeb_count(String webCount)
 {
  web_count = webCount;
 }
 public String getWeb_url()
 {
  return web_url;
 }
 public void setWeb_url(String webUrl)
 {
  web_url = webUrl;
 }
 
 public String getConfigFileName()
 {
  return this.configFileName;
 }
 public void setConfigFileName(String cfgFileName)
 {
  this.configFileName = cfgFileName;
 }
}
 

 

4. ExecCmd.java 类

 

 

package com.zhangzhen.cmd;

 

import java.io.File;
import java.io.IOException;


public class ExecCmd
{
 //Runtime runtime ;
   
 public static void exec(SystemVars configInfo)
 {
  String cmd = "netsh -f "+configInfo.getFile_url()+configInfo.getConfigFileName()+".txt";
  try
  {
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec(cmd);
  }
  catch(IOException e)
  {
   System.out.println("+------>"+e.getMessage());
  }
 }
 
 
 public static void dhcp()
 {
  File dhcp = new File("D:\\IP_CONFIG\\dhcp.txt");
  String [] str = new String[5];
  str[0]="pushd interface ip";
  str[1]="set address name="+"本地连接 "+"source=dhcp";
  str[2]="set dns name="+"本地连接 "+"source=dhcp register=PRIMARY ";
  str[3]="set wins name="+"本地连接 "+"source=dhcp";
  str[4]="popd";
  
  try
  {
      dhcp.createNewFile();
  }
  catch(IOException ie)
  {
   ie.printStackTrace();
  }
  
  ConfigFile.createFile("D:\\IP_CONFIG\\dhcp.txt", str);
  
  String cmd = "netsh -f "+"D:\\IP_CONFIG\\dhcp.txt";
  try
  {
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec(cmd);
     }
  catch(IOException e)
  {
   System.out.println("+------>"+e.getMessage());
  }
 }
}
 

本人也是初学Java,这些代码已经在eclipse里运行过没有错误,但是肯定还有不足,欢迎学习交流。

本文出自 “计科小鸟” 博客,请务必保留此出处http://1249022.blog.51cto.com/1239022/603540

你可能感兴趣的:(java,方法,IP,职场,休闲)