문제

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