【问题标题】:Getting FileNotFoundException when trying to run a java program through CMD using input and output files尝试使用输入和输出文件通过 CMD 运行 java 程序时出现 FileNotFoundException
【发布时间】:2016-03-23 18:17:19
【问题描述】:

当我尝试通过 Eclipse 运行此代码时,它工作正常,但是当我尝试使用“java MainClass >result.txt”通过 CMD 运行它时,我得到一个 FileNotFoundException。 这是有问题的代码:

导入 java.io.; 导入 java.util.;

公共类 MainClass {

static int cellNumber;
static int freeSpace;
static int randomResult;
static int chosen;
static int choiceSize;

public static void main(String[] args)
{
    Scanner in = null;
    try 
    {
        in = new Scanner(new FileReader("C:\\users\\Alon\\workspace\\ex2temp\\bin\\input.txt"));
        FileWriter fw = new FileWriter("C:\\users\\Alon\\workspace\\ex2temp\\bin\\result.txt");
        PrintWriter pw = new PrintWriter(fw);
        chosen = getRandomInt();
        pw.printf("Choice=%d", chosen);
        pw.println();
        while (in.hasNext())
        {
            cellNumber = in.nextInt();
            freeSpace = in.nextInt();

            if (sizeOfChosen(chosen) <= freeSpace)
            {
                pw.printf("%d", cellNumber);
                pw.println();
                break;
            }
        }
        if (!in.hasNext())
        {
            pw.println("Cannot allocate memory");
            pw.println();
        }
        pw.close();
        fw.close();
        in.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

有人可以帮忙吗?谢谢:)

【问题讨论】:

  • 在您的问题中包含堆栈跟踪。
  • C:\\users\\... 可能被隐藏(我遇到过这个问题),请尝试将文件放在其他位置。
  • 这是我在 CMD 中得到的堆栈跟踪:java.io.FileNotFoundException: C:\users\Alon\workspace\ex2temp\bin\result.txt(进程无法访问该文件,因为它是被另一个进程使用)在 java.io.FileOutputStream.open(Unknown Source) 在 java.io.FileOutputStream.(Unknown Source) 在 java.io.FileOutputStream.(Unknown Source) 在 java.io.FileOutputStream.open0(Native Method) .(Unknown Source) at java.io.FileWriter.(Unknown Source) at MainClass.main(MainClass.java:20)

标签: java file cmd filenotfoundexception


【解决方案1】:

您正在使用“.../ext2temp/bin/..”中的文件,我认为它是 Eclipse 的输出文件夹。使用您拥有原始文件的路径。

【讨论】:

  • 您的意思是将类文件和输入文件向上移动一级并尝试从那里运行吗?如在 - 在 bin 目录之外?
  • 不是类文件。我说的是input.txt和result.txt
  • 避免异常!!谢谢!!我将 input.txt 上移了一级。 result.txt 是在运行后形成的,但是现在,当我在 CMD 上运行“java MainClass>result.txt”时,我得到一个空的 result.txt,而当我从 Eclipse 运行它时,结果。 txt 中包含正确的数据。
  • 澄清几点: 1. 我应该运行这段代码 20 次。第一次,result.txt 不存在。它应该是第一次形成,到最后,它应该包含 2 行数据。 2. 再运行 19 次后,我应该在同一个 result.txt 文件中有 40 行数据。 (建立日志文件的种类和练习)。我在这里做错了什么?
【解决方案2】:

为了在同一个文件上创建连续写入,我必须将文本附加到现有文件中。我在创建 FileWriter 时添加了“, true”。然后,我创建了一个接收 FileWriter 对象的新 BufferedWriter,最后将 PrintWriter 接收对象更改为 bufferredWriter。这样,每次我运行程序时,都会在旧数据的下方形成 2 行新数据,并得到一个“日志文件”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多