现在的位置: 首页 > 综合 > 正文

java判断是window系统还是Linux系统,并获取其IP地址及文件上传

2014年02月10日 ⁄ 综合 ⁄ 共 2402字 ⁄ 字号 评论关闭

这是upload类的方法:

public class Upload {
    public static String upload(FormFile formfile,String dirPath,int port){
        String savePath="";
         String ip="";
        try{
            String filename = formfile.getFileName().trim(); // 文件名
             if (!"".equals(filename)) {
              InputStream ins = formfile.getInputStream();
              String currentPath=dirPath+ File.separatorChar + filename;  //文件保存路径
              OutputStream os = new FileOutputStream(currentPath);
              int bytesRead = 0;
              byte[] buffer = new byte[8192];
              while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
               os.write(buffer, 0, bytesRead);
              }
              boolean isWindows=isWindowsOS();  //判断是否是windows系统
              if(isWindows){
                 InetAddress address=InetAddress.getLocalHost();
                 ip=address.getHostAddress();  //获取ip地址
                 System.out.println("windows ip地址:"+ip);
              }
              else{    //如果是Linux系统
                 ip=Tools.getLinuxIP();
                 System.out.println("linux ip地址:"+ip);
             }
              savePath="http://"+ip+":"+port+"/channelProject/upload/";   //保存到数据库的地址,图片上传到服务器端
              
              savePath+=filename;
              os.close();
              ins.close();
             }
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传出现错误!!");
        }
        return savePath;
    }
      
/*
* @return true---是Windows操作系统
*/
public static boolean isWindowsOS(){
    boolean isWindowsOS = false;
    String osName = System.getProperty("os.name");
    if(osName.toLowerCase().indexOf("windows")>-1){
      isWindowsOS = true;
    }
    return isWindowsOS;
 }
}

 

 

以下是Tools类下的getLinux的方法:

 

public class Tools {
    public static String getLinuxIP() throws SocketException{
        //根据网卡取本机配置的IP  
        Enumeration netInterfaces=NetworkInterface.getNetworkInterfaces();  
        InetAddress ipAddress = null;  
        String ip="";
        while(netInterfaces.hasMoreElements())  
        {  
            NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement(); 
            if(!ni.getName().equals("eth0")){
                continue;
            }
            else{
                Enumeration<?> e2=ni.getInetAddresses();
                while(e2.hasMoreElements()){
                     ipAddress=(InetAddress) e2.nextElement();
                     if(ipAddress instanceof Inet6Address)
                         continue;
                     ip=ipAddress.getHostAddress();
                     System.out.println("getLinuxIp:"+ip);
                }
                break;
            }
        } 
        return ip;
    }
}

抱歉!评论已关闭.