我在他们各自的文件中有以下来自一本书的示例代码,每个文件都与其中定义的接口或类具有相同的名称:
Logger.java
package logging;
public interface Logger
{
boolean connect();
boolean disconnect();
boolean log(String msg);
}
LoggerFactory.java
package logging;
public abstract class LoggerFactory
{
public final static int CONSOLE = 0;
public final static int FILE = 1;
public static Logger newLogger(int dstType, String... dstName)
{
switch (dstType)
{
case CONSOLE: return new Console(dstName.length == 0 ? null : dstName[0]);
case FILE : return new File(dstName.length == 0 ? null : dstName[0]);
default : return null;
}
}
}
Console.java
package logging;
class Console implements Logger
{
private String dstName;
Console(String dstName)
{
this.dstName = dstName;
}
@Override
public boolean connect()
{
return true;
}
@Override
public boolean disconnect()
{
return true;
}
@Override
public boolean log(String msg)
{
System.out.println(msg);
return true;
}
}
File.java
package logging;
class File implements Logger
{
private String dstName;
File(String dstName)
{
this.dstName = dstName;
}
@Override
public boolean connect()
{
if (dstName == null)
return false;
System.out.println("opening file " + dstName);
return true;
}
@Override
public boolean disconnect()
{
if (dstName == null)
return false;
System.out.println("closing file " + dstName);
return true;
}
@Override
public boolean log(String msg)
{
if (dstName == null)
return false;
System.out.println("writing "+msg+" to file " + dstName);
return true;
}
}
TestLogger.java
// package logging;
import logging.Logger;
import logging.LoggerFactory;
public class TestLogger
{
public static void main(String[] args)
{
Logger logger = LoggerFactory.newLogger(LoggerFactory.CONSOLE);
if (logger.connect())
{
logger.log("test message #1");
logger.disconnect();
}
else
System.out.println("cannot connect to console-based logger");
logger = LoggerFactory.newLogger(LoggerFactory.FILE, "x.txt");
if (logger.connect())
{
logger.log("test message #2");
logger.disconnect();
}
else
System.out.println("cannot connect to file-based logger");
logger = LoggerFactory.newLogger(LoggerFactory.FILE);
if (logger.connect())
{
logger.log("test message #3");
logger.disconnect();
}
else
System.out.println("cannot connect to file-based logger");
}
}
所有这些文件都在一个名为logger
. 这本书说执行javac TestLogger.java
应该在目录中找到并编译所有必要的类文件logger
,但我得到一个错误
TestLogger.java:3: error: package logging does not exist
import logging.Logger;
^
其次是其他错误,主要与找不到logging
包有关。为什么这个程序不编译?我尝试创建指向父文件夹的 CLASSPATH 系统变量,logging
并尝试
javac -classpath "parent_folder_of_logging" TestLogger.java
但没有任何效果。这里有什么问题,我该如何解决?