linux终端编译执行java代码

安装好相应环境后,将java文件放到指定的目录下,下面举例App.java,代码如下:

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        //App app = new App();
        getHostIp();
    }
    
    private static String getHostIp()
{
StringBuilder IFCONFIG = new StringBuilder();
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip地址为:"+inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress() 
&& !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress())
{
IFCONFIG.append(inetAddress.getHostAddress().toString());
System.out.println("------过滤后ip地址为:"+inetAddress.getHostAddress().toString());
}
}
}
}
catch (SocketException ex)
{
System.out.println(ex.toString());
}
return IFCONFIG.toString();
}

}

注意这种情况下没有包,此时编译如下:


会生成一个App.class文件

运行如下:



在有包的情况下,此时代码如下:

package com.finalpro.project.finalproject;


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


/**
 * Hello world!
 *
 */
public class App 
{
//final定义的变量只能赋值一次,也就是说如果已经赋值过了那么不能再次赋值
public final int a;
public final int b;

public App() {
   a = 1;
   b = 9;
   System.out.println("a:"+a+",b:"+b);
}

    public static void main( String[] args )
    {
        //App app = new App();
        getHostIp();
    }
    
    private static String getHostIp()
{
StringBuilder IFCONFIG = new StringBuilder();
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip地址为:"+inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress() 
&& !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress())
{
IFCONFIG.append(inetAddress.getHostAddress().toString());
System.out.println("------过滤后ip地址为:"+inetAddress.getHostAddress().toString());
}
}
}
}
catch (SocketException ex)
{
System.out.println(ex.toString());
}
return IFCONFIG.toString();
}

}

编译如下:


此时会出现一个文件夹,路径是根据包名产生的。执行如下:


猜你喜欢

转载自blog.csdn.net/weixin_39935887/article/details/80927907