在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代碼,并根據需要進行優化。