命令行调用同包类构造器时出现“找不到符号”错误排查
同包类调用时出现"cannot find symbol"错误的排查与解答
我尝试从同包下的另一个类调用FileRead类及其Display、Contents方法。FileRead类在Eclipse中可正常运行,命令行也能编译运行,但编译调用它的FileReadShow类时,出现如下"cannot find symbol"错误:
javac filereadshow.java filereadshow.java:112: error: cannot find symbol FileRead myTextFile = new FileRead(); ^ symbol: class FileRead location: class FileReadShow filereadshow.java:112: error: cannot find symbol FileRead myTextFile = new FileRead(); ^ symbol: class FileRead location: class FileReadShow 2 errors
我已经排查过拼写问题、移除过main方法,尝试过重启IDE/电脑、清理项目、新建类等操作,但问题仍未解决。请问:
- 是否是构造器的对象引用调用有误?
- 问题出在FileRead类本身还是对象引用语句?
附:相关代码
FileRead类代码
public class FileRead { static String theFile; Scanner myScanner = new Scanner (System.in); static List<String> fileArray = new ArrayList<String>(); static StringBuffer stringBuff = new StringBuffer(); public FileRead() { System.out.println ("Enter your file: "); theFile = myScanner.nextLine(); try { myScanner = new Scanner(new File(theFile)); FileReader myFileReader = new FileReader(theFile); BufferedReader buffRead = new BufferedReader(myFileReader); while ((theFile = buffRead.readLine()) != null) { fileArray.add(theFile); } buffRead.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String Contents() { for (String str : fileArray) { stringBuff.append(str); stringBuff.append("\n"); } String str = stringBuff.toString(); return (str); } public void Display() { for (int i = 0; i < fileArray.size(); i++) { System.out.println ("Line # " + (i + 1) + " " + fileArray.get(i)); } } public static void main (String[] args) { //FileRead textFile = new FileRead(); //textFile.Display(); //textFile.Contents(); } }
FileReadShow类代码
public class FileReadShow { public static void main (String[] args) { try { FileRead myTextFile = new FileRead(); myTextFile.Contents(); myTextFile.Display(); } catch (Exception e) { e.printStackTrace(); } } }
问题解答
构造器的对象引用调用本身没有语法错误,
FileRead myTextFile = new FileRead();的写法完全符合Java语法逻辑,不是错误根源。问题既不在FileRead类本身,也不在对象引用语句:
- FileRead类能单独编译运行,说明类本身没有语法或功能性问题;
- 核心问题出在命令行编译的方式:当你单独编译
filereadshow.java时,javac找不到对应的FileRead.class文件(可能是没提前编译FileRead类,或者编译后的class文件不在当前目录)。 - 正确的命令行操作步骤:
- 先编译FileRead类:
javac FileRead.java - 再编译FileReadShow类:
javac FileReadShow.java - 或者一次性编译同目录下所有Java文件:
javac *.java
- 先编译FileRead类:
- 同时要确保两个类的源文件和编译后的class文件都在同一目录下(因为没有显式声明package,默认使用当前目录作为包路径)。
额外提示(非当前错误原因,但需注意)
你的FileRead类存在几个潜在问题:
fileArray和stringBuff被声明为static,多次实例化FileRead时会导致数据共享覆盖,建议移除static修饰符;- 构造器中重新赋值
myScanner,原Scanner对象会被丢弃,存在资源泄漏风险,建议合理管理IO资源。
内容的提问来源于stack exchange,提问作者NobleRuckus
相关产品推荐
相关产品推荐

