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

后端 未结 3 1944
故里飘歌
故里飘歌 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:36

    You probably should use backslash instead of slash:

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

    You can also try to type double backslash:

    p.concat("\\HackGSU\\bad_words.txt");
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-27 19:50

    Looking at the error it doesn't look like you are getting the full path. Instead of

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

    Try

    p = p.concat("/HackGSU/bad_words.txt");
    
    0 讨论(0)
提交回复
热议问题