在Debian上编译Java代码可以通过以下步骤和技巧来完成:
sudo apt update
sudo apt install default-jdk
java -version
javac -version
/etc/environment
文件,添加以下行(请根据你安装的JDK版本调整路径):JAVA_HOME="/usr/lib/jvm/java-<version>-openjdk-amd64"
source /etc/environment
/etc/environment
或 ~/.bashrc
文件中添加以下行:PATH="$JAVA_HOME/bin:$PATH"
source /etc/environment
编译Java源代码:
javac
命令编译Java文件。例如,编译一个名为 HelloWorld.java
的文件:javac HelloWorld.java
.class
文件。运行Java程序:
java
命令运行编译后的字节码文件:java HelloWorld
使用 javax.tools
包进行动态编译:
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class RuntimeCompiler {
private JavaCompiler javaCompiler;
public RuntimeCompiler() {
this.javaCompiler = ToolProvider.getSystemJavaCompiler();
}
public Class<?> compileAndLoad(String fullName, String sourceCode) throws ClassNotFoundException, IOException {
DiagnosticCollector<? super JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavaFileManager fileManager = javaCompiler.getStandardFileManager(diagnosticCollector, null, null);
List<JavaFileObject> javaFileObjectList = new ArrayList<>();
javaFileObjectList.add(new JavaSourceObject(fullName, sourceCode));
JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, diagnosticCollector, null, null, javaFileObjectList);
if (task.call()) {
return fileManager.getClassLoader(null).loadClass(fullName);
}
System.out.println(diagnosticCollector.getDiagnostics().get(0).getLineNumber());
System.out.println(diagnosticCollector.getDiagnostics().get(0).getColumnNumber());
System.out.println(diagnosticCollector.getDiagnostics().get(0).getMessage(Locale.ENGLISH));
System.out.println(diagnosticCollector.getDiagnostics().get(0).getSource());
System.out.println(diagnosticCollector.getDiagnostics().get(0).getCode());
return null;
}
}
使用脚本自动化编译和运行:
compile.sh
:#!/bin/sh
javac -sourcepath src -d bin src/com/sakura/calculator/CalculatorTest.java
java -cp bin com.sakura.calculator.CalculatorTest
chmod +x compile.sh
./compile.sh
update-alternatives
命令管理Java版本:
sudo update-alternatives --config java
环境变量不生效:
~/.bashrc
文件的配置是否正确,并重新登录或使用 source ~/.bashrc
使之生效。路径问题:
通过以上步骤和技巧,你可以在Debian系统上高效地编译和运行Java代码,并根据需要进行优化。