【问题标题】:Eclipse: Running with argument and not finding text fileEclipse:使用参数运行但找不到文本文件
【发布时间】:2013-12-26 23:52:56
【问题描述】:

我正在尝试在Algorithms (4th ed.) 中运行一个程序

package binarysearch;
import edu.princeton.cs.introcs.*;
import java.util.Arrays;

public class BinarySearch {
    public static int rank(int key, int[] a) 
    {
    int lo = 0;
    int hi = a.length - 1;
    while (lo <= hi)
    {
        int mid = lo + (hi - lo) / 2;
        if (key < a[mid]) hi = mid - 1;
        else if (key > a[mid]) lo = mid + 1;
        else return mid;
    }
    return -1;
    }

    public static void main(String[] args) 
    {
    int[] whitelist = In.readInts(args[0]);

    Arrays.sort(whitelist);

    while(!StdIn.isEmpty())
    {
        int key = StdIn.readInt();
        if (rank(key, whitelist) == -1)
        StdOut.println(key);
    }
    }
}

运行程序的命令是

% java BinarySearch tinyW.txt &lt; tinyT.txt

我将文本文件添加到要运行的包中。

我还在运行配置中添加了所需的参数。

但是 Eclipse 告诉我这个错误信息。

我不确定为什么 Eclipse 无法打开该文件。我也手动将文件权限设置为 777。有什么想法吗?

【问题讨论】:

  • In.readInts 是否需要文件名?

标签: java eclipse


【解决方案1】:

我认为您正在尝试重定向您的输入。看这个。

所以 tinyW.txt 是你的程序参数,没关系。
但 tinyT.txt 不是,你只是想
将 tinyT.txt 重定向到标准输入。

https://bugs.eclipse.org/bugs/show_bug.cgi?id=155411

似乎 Eclipse 不支持这个。

我会尝试从 Eclipse 外部运行它。

另请参阅。 Eclipse reading stdin (System.in) from a file

【讨论】:

  • 请查看堆栈跟踪。我不认为重定向输入是这里的根本原因。
【解决方案2】:

In class的源码,好像默默吞下了IOException

Could not open tinyW.txt

这会导致NullPointerException 下线,因为In 在内部使用的Scanner 未初始化。

如果我不得不猜测,这个异常的根本原因是FileNotFoundException

不要将文件放在类的包中,而是将其放在项目目录的根目录中。 Eclipse 通常从那个目录运行你的应用程序,所以所有的相对路径,比如tinyW.txt 都是相对于那个目录的。

一旦你解决了这个问题,就知道使用 shell 重定向操作符作为 java 参数不会产生预期的效果。 Eclipse 正在像这样运行您的应用程序

java binarysearch.BinarySearch "tinyW.txt < tinyT.txt"

您可以明显看到 &lt; 在引号内,因此不被 shell 解析器处理。


考虑使用除提供给您的 In 类以外的任何东西。这是一个可怕的混乱,吞下异常等等。

【讨论】:

  • 感谢您的帮助。我决定在 Eclipse 之外运行它。
猜你喜欢
  • 2011-02-17
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多