How to read a file that is located in the project folder java

后端 未结 3 1941
故里飘歌
故里飘歌 2021-01-27 19:07

Using eclipse, I have a file titled bad_words.txt in my project folder titled HackGSU. I want locate the file and read the contents of the file. I saw this answer how to read te

3条回答
  •  粉色の甜心
    2021-01-27 19:42

    If your resource is already in the classpath, you don't need to make use of relative paths with the File class. You can easily obtain it from the classpath like:

    java.net.URL url = getClass().getResource("bad_words.txt");
    File file = new File(url.getPath());
    

    or even directly to an inputstream:

    InputStream in = getClass().getResourceAsStream("bad_words.txt");
    

    Since you have a static method use:

    InputStream in = YourClass.class.getResourceAsStream("bad_words.txt");
    

    Furthermore, as I mentioned it already in my comment:

    p.concat("/HackGSU/bad_words.txt");
    

    does not concat to p but returns a new concatenated String, because Strings are immutable. Simply use: p+="/HackGSU/bad_words.txt" instead

提交回复
热议问题