Java project path to NetBeans 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);
}
}

My project structure is set 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 textfile input Txt is placed in a directory named test, which is located in the same directory as build, dist and Src. Then you should enter the parameter of FileReader so that I can still find the file?

Solution

When running in the NetBeans IDE, the working directory is the root directory of the project, so answer your question "test / input. TXT"

Note, however, that although the test code is perfectly correct, using relative paths in the final (production) code can be trickier It might be a better solution to wrap a file in a jar as a resource and open it as a resource, or of course use an absolute path

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>