Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
问题1.程序员安装 .jar 文件中包含的新库。为了从代码中访问库,他将 CLASSPATH 环境变量设置为指向新的 .jar 文件。现在他发现他在尝试启动简单应用程序时收到错误消息:
java Hello Exception in thread "main" java.lang.NoClassDefFoundError: Hello
在这种情况下,Hello 类被编译成当前目录中的 .class 文件 然而 java 命令似乎找不到它。出了什么问题?
答案1.仅当类出现在类路径中时才会找到该类。默认情况下,类路径由当前目录组成。如果设置了 CLASSPATH 环境变量,并且不包含当前目录,则启动程序将无法再在当前目录中找到类。解决方案是更改 CLASSPATH 变量以包含当前目录。例如,如果 CLASSPATH 值为 c:\java\newLibrary.jar(Windows)或 /home/me/newLibrary.jar(UNIX 或 Linux),则需要更改为 .;c:\java\newLibrary.jar 或 .:/home/me/newLibrary.jar。
练习1.
编写一个应用程序 PersistentEcho,具有以下功能:
PersistentEcho,则会打印出这些参数。它还将打印出的字符串保存到属性,并将属性保存到名为 PersistentEcho.txt 的文件中PersistentEcho,它将查找名为 PERSISTENTECHO 的环境变量。如果该变量存在,PersistentEcho 将打印出其值,并以与命令行参数相同的方式保存该值。PersistentEcho,并且未定义 PERSISTENTECHO 环境变量,它将从 PersistentEcho.txt 中获取属性值并将其打印出来。答案1.
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class PersistentEcho {
public static void main (String[] args) {
String argString = "";
boolean notProperty = true;
// Are there arguments?
// If so retrieve them.
if (args.length > 0) {
for (String arg: args) {
argString += arg + " ";
}
argString = argString.trim();
}
// No arguments, is there
// an environment variable?
// If so, //retrieve it.
else if ((argString = System.getenv("PERSISTENTECHO")) != null) {}
// No environment variable
// either. Retrieve property value.
else {
notProperty = false;
// Set argString to null.
// If it's still null after
// we exit the try block,
// we've failed to retrieve
// the property value.
argString = null;
FileInputStream fileInputStream = null;
try {
fileInputStream =
new FileInputStream("PersistentEcho.txt");
Properties inProperties
= new Properties();
inProperties.load(fileInputStream);
argString = inProperties.getProperty("argString");
} catch (IOException e) {
System.err.println("Can't read property file.");
System.exit(1);
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch(IOException e) {};
}
}
}
if (argString == null) {
System.err.println("Couldn't find argString property");
System.exit(1);
}
// Somehow, we got the
// value. Echo it already!
System.out.println(argString);
// If we didn't retrieve the
// value from the property,
// save it //in the property.
if (notProperty) {
Properties outProperties =
new Properties();
outProperties.setProperty("argString",
argString);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream =
new FileOutputStream("PersistentEcho.txt");
outProperties.store(fileOutputStream,
"PersistentEcho properties");
} catch (IOException e) {}
finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch(IOException e) {};
}
}
}
}
}