I am facing an issue while trying to resolve a file path using relative paths in Java. I am not sure where I am failing at. Could you please help me out? Thanks!

@Test
public void testObjectNotNull() throws Exception{
    FileReader fileReader = new FileReader(getClass().getResource("./JavaPractice/resources/tests/codeeval/fileReaderTest.txt").toString());
    assertNotNull(fileReader);
}

Exception:

java.lang.NullPointerException
    at components.com.codeeval.FileReader.FileReaderTest.testObjectNotNull(FileReaderTest.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

Directory Structure:

JavaPractice

--resources.tests.codeeval.fileReaderTest.txt (File that I am trying to access)

--tests.components.com.codeeval.FileReader.FileReaderTest.java (junit which is trying to access the above file)

有帮助吗?

解决方案

Resources are not files. They are typically JAR file entries. You should use the resource API of Class or ClassLoader. That can return you an InputStream.

其他提示

Your issue is because this

getClass().getResource("./JavaPractice/resources/tests/codeeval/fileReaderTest.txt")

is null. You are reading from the classpath and not a relative path per-se SO Change your code to
getClass().getResource("tests/codeeval/fileReaderTest.txt") and ensure that the resources folder is on your classpath. Also read up on loading from classpath

try this

InputStream in = Your_Class.class.getClassLoader().getResourceAsStream("resources/tests/codeeval/abc.txt");

 assertNotNull(in);
 Reader fr = new InputStreamReader(in, "utf-8");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top