admin管理员组

文章数量:1195292

I'm trying to read a file called "words.txt", which sits in my src folder.

My code currently looks like this:

package hangman;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class GetHangmanWords {
    public static String[] get() throws IOException {
        InputStream in = GetHangmanWords.class.getClass().getClassLoader().getResourceAsStream("words.txt");
        
        InputStreamReader inReader = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(inReader);
        
        String[] words = {};
        ArrayList<String> lines = new ArrayList<String>();
        while (reader.readLine() != null) {
            lines.add(reader.readLine());
        }
        
        words = (String[]) lines.toArray();
        return words;
    }

}

But when I try to call this code like this:

package hangman;

import java.io.IOException;

public class Test {
    public static void main (String [] args) throws IOException {
        String[] words = GetHangmanWords.get();
    }

}

I get:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.ClassLoader.getResourceAsStream(String)" because the return value of "java.lang.Class.getClassLoader()" is null
    at hangman/hangman.GetHangmanWords.get(GetHangmanWords.java:11)
    at hangman/hangman.Test.main(Test.java:7)

I don't understand enough about the mechanics at work here, since I'm fairly new to java, and I can't make sense of other explanations. If someone could help me, that would be much appreciated!

I'm trying to read a file called "words.txt", which sits in my src folder.

My code currently looks like this:

package hangman;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class GetHangmanWords {
    public static String[] get() throws IOException {
        InputStream in = GetHangmanWords.class.getClass().getClassLoader().getResourceAsStream("words.txt");
        
        InputStreamReader inReader = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(inReader);
        
        String[] words = {};
        ArrayList<String> lines = new ArrayList<String>();
        while (reader.readLine() != null) {
            lines.add(reader.readLine());
        }
        
        words = (String[]) lines.toArray();
        return words;
    }

}

But when I try to call this code like this:

package hangman;

import java.io.IOException;

public class Test {
    public static void main (String [] args) throws IOException {
        String[] words = GetHangmanWords.get();
    }

}

I get:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.ClassLoader.getResourceAsStream(String)" because the return value of "java.lang.Class.getClassLoader()" is null
    at hangman/hangman.GetHangmanWords.get(GetHangmanWords.java:11)
    at hangman/hangman.Test.main(Test.java:7)

I don't understand enough about the mechanics at work here, since I'm fairly new to java, and I can't make sense of other explanations. If someone could help me, that would be much appreciated!

Share Improve this question edited Jan 23 at 13:34 Dante_05 asked Jan 23 at 7:59 Dante_05Dante_05 113 bronze badges 8
  • In this case you don't really want to load the file as a resource, since that kind of implies that the file will never change. I would pass the path as an application parameter and read it as a file with words = Files.readAllLines(Path.of(Argos[0])); Be careful about the path you use. You need to know the current directory to get that right – g00se Commented Jan 23 at 8:19
  • 2 You should be calling GetHangmanWords.class.getResourceAsStream("words.txt"), assuming the resource is bundled with the same code – DuncG Commented Jan 23 at 8:53
  • @g00se Well, the file will indeed never change. It's a static file that only stores the words for a hangman game I'm making and is never changed by the program. Nevertheless, how would I get the path? I can of course just input the current path of the file inside of my project folder, but once I package the program as a jar, that internal logic breaks down – Dante_05 Commented Jan 23 at 9:03
  • @DuncG Tried that, now I'm getting "Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader 'bootstrap')" – Dante_05 Commented Jan 23 at 9:09
  • @g00se Well, the file will indeed never change. That's different in that case. I would probably do something like: public static String[] get() throws IOException {String[] words = null;try (InputStream in = GetHangmanWords.class.getResourceAsStream("/words.txt")) {words = new Scanner(in).useDelimiter("\\R").tokens().toArray(String[]::new);}return words;} – g00se Commented Jan 23 at 10:53
 |  Show 3 more comments

2 Answers 2

Reset to default 1

A resource lookup does not work with GetHangmanWords.class.getClass() ... as that means you looking for a resource of java.lang.Class rather than the class definition of GetHangmanWords. Instead use:

InputStream in = GetHangmanWords.class.getResourceAsStream("words.txt")

You could save a lot of typing and use built-in calls of BufferedReader to retrieve a list or array of String:

public static List<String> get() throws IOException {
    InputStream words = GetHangmanWords.class.getResourceAsStream("words.txt");

    try(var reader = new BufferedReader(new InputStreamReader(words))) {
        return reader.lines().toList();
    }
}

If really wanting ArrayList use a different return:

return reader.lines().collect(Collectors.toCollection(ArrayList::new));

I found a solution that worked! Here's my current code. I've forgone the conversion from an ArrayList to an Array, and am now working with an ArrayList on the other side:

package hangman;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class GetHangmanWords {
    public static ArrayList<String> get() throws IOException {
        InputStream in = GetHangmanWords.class.getResourceAsStream("words.txt");
        
        InputStreamReader inReader = new InputStreamReader(in);
        BufferedReader reader = new BufferedReader(inReader);
        
        ArrayList<String> lines = new ArrayList<String>();
        while (lines.contains(null) != true) {
            lines.add(reader.readLine());
        }
        
        lines.removeLast();
    
        return lines;
    }

}

Thanks especially to @DuncG for getting me on the right path!

本文标签: javaHow to get the content of a file from the src folderStack Overflow