getResourceAsStream returns null

前端 未结 16 2548
臣服心动
臣服心动 2020-11-22 04:00

I\'m loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows:

/src/initialization/Life         


        
16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 04:20

    Don't use absolute paths, make them relative to the 'resources' directory in your project. Quick and dirty code that displays the contents of MyTest.txt from the directory 'resources'.

    @Test
    public void testDefaultResource() {
        // can we see default resources
        BufferedInputStream result = (BufferedInputStream) 
             Config.class.getClassLoader().getResourceAsStream("MyTest.txt");
        byte [] b = new byte[256];
        int val = 0;
        String txt = null;
        do {
            try {
                val = result.read(b);
                if (val > 0) {
                    txt += new String(b, 0, val);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } 
        } while (val > -1);
        System.out.println(txt);
    }
    

提交回复
热议问题