[英]NetBeans Java Project Path of Text File
I have the following code to read a text file. 我有以下代码来读取文本文件。
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);
}
}
I have my project structure set up as follows: 我的项目结构设置如下:
build/ directory contains class
dist/ directory contains the jar file
src/ directory contains source
input.txt the text file to read
If I put my textfile input.txt
into a directory called test
which is of the same directory as build
, dist
, and src
, what should go into the parameter of filereader
so that I can still find this file? 如果我把我的文本文件
input.txt
放到一个名为test
的目录中,该目录与build
, dist
和src
属于同一目录,那么应该进入filereader
的参数,以便我仍然可以找到这个文件?
When running inside the Netbeans IDE the working directory is the root of the project, so to answer your question, "test/input.txt". 在Netbeans IDE中运行时,工作目录是项目的根目录,因此要回答您的问题“test / input.txt”。
Note however that while this is perfectly fine for testing code, working with relative paths like this in final (production) code can be trickier. 但请注意,虽然这对于测试代码非常好,但在最终(生产)代码中使用这样的相对路径可能会更棘手。 In those cases wrapping the file as a resource in the jar and opening it as a resourcestream may be a better solution, or of course working with absolute paths.
在那些情况下,将文件作为资源包装在jar中并将其作为资源流打开可能是更好的解决方案,或者当然使用绝对路径。
如果您知道子目录的名称,请使用
Scannner in = new Scanner(new FileReader("test/input.txt"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.