1

它编译得很好,但是当我尝试从控制台运行它时,我得到了一个 ClassNotFoundException 错误。但如果我从 Eclipse 运行它,它工作正常。为什么?

我使用“javac FileIO.java”编译并使用“java FileIO”运行它。

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileOutputStream;

public class FileIO {
public static void main(String[] args){
    PrintWriter pw = null;
    BufferedReader bfr = null;
    String linea = null;

    try{
        bfr = new BufferedReader(new FileReader("Records"));
        linea = bfr.readLine();
    } catch(FileNotFoundException fnfex){
            System.out.println("Check you have reading/writing access.");
    } catch(IOException ioex){
            ioex.printStackTrace();
    }

    try{
        pw = new PrintWriter(new FileOutputStream("Copy Records"));
    } catch(FileNotFoundException fnfex){
            System.out.println("Check you have reading/writing access.");
    }

    while(linea != null){
        pw.println(linea);
        try{
            linea = bfr.readLine();
        } catch(IOException ioex){
                ioex.printStackTrace();
        }
    }

    try{
        bfr.close();
    } catch(IOException ioex){
            ioex.printStackTrace();
    }

    pw.close();
}
}`

完成 StackTrace:

`Exception in thread "main" java.lang.NoClassDefFoundError: FileIO/java
Caused by: java.lang.ClassNotFoundException: FileIO.java
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: FileIO.java.  Program will exit.

`

4

2 回答 2

6

错误消息看起来像您正在调用

java FileIO.java

代替

java FileIO
于 2012-02-28T20:23:52.350 回答
2

您正在尝试运行 FileIO.java;它将“java”视为 FileIO 包中的类。

于 2012-02-28T20:24:42.377 回答