NetBeans文本文件的Java项目路径

我有以下代码来读取一个文本文件.
public static void main(String[] args)
{
    try 
    {
    Scanner in = new Scanner(new FileReader("input.txt"));
    while(in.hasNext())
    {
        System.out.println(in.next());
    }
} 
catch (FileNotFoundException ex) 
{
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null,ex);
}
}

我的项目结构设置如下:

build/ directory contains class
dist/  directory contains the jar file 
src/ directory contains source
input.txt the text file to read

如果我将textfile input.txt放入一个名为test的目录中,该目录与build,dist和src位于同一个目录,那么应该进入filereader的参数,以便我仍然可以找到这个文件

解决方法

当运行在Netbeans IDE中时,工作目录是项目的根目录,所以要回答你的问题“test / input.txt”.

但是请注意,尽管测试代码完全正确,但在最终(生产)代码中使用相对路径的工作可能更为棘手.在将文件作为资源包装在jar中并将其作为资源打开的情况下,可能是更好的解决方案,或者当然使用绝对路径.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...