我有以下代码来读取文本文件。
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
如果我将我的文本文件input. txt
放入一个名为test
的目录中,该目录与build
、dist
和src
属于同一目录,那么filereader
的参数中应该包含什么,以便我仍然可以找到这个文件?
在Netbean内部运行时IDE工作目录是项目的根目录,因此要回答您的问题,请使用“test/input. txt”。
但是请注意,虽然这对于测试代码来说非常好,但在最终(生产)代码中使用这样的相对路径可能更棘手。在这些情况下,将文件作为资源包装在jar中并将其作为资源流打开可能是更好的解决方案,当然也可以使用绝对路径。
如果您知道子目录的名称,只需使用
Scannner in = new Scanner(new FileReader("test/input.txt"));