我有從一本書在各自文件中的以下示例代碼,每個文件具有相同的名稱在它定義的接口或類:包<name>不存在錯誤
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
但沒有任何工作。這裏有什麼問題,我該如何解決?
'TestLogger'不應該在'logging'目錄下,除非它被聲明在包'logging'中。 Ernesto說,你的目錄結構應該使你的軟件包結構基本上可以從根目錄編譯。 –
好的,我明白了。我在TestLogger的位置上犯了一個錯誤。但是,如果我將TestLogger.java文件中的'package logger'放入行,爲什麼它仍然不能編譯? – user13267
因爲那麼你需要根據Ernesto的回答從* parent *目錄編譯它。 –