Getting input stream from classpath file

After reading this question, I tried the following while reading a file from the classpath of a maven project built with IntelliJ:

public class testTemplateManager {

private TemplateManager templateManager;
private String m_includePath;

public void createTemplateManager() {
    String relativePath = "/src/main/java/com/eprosima/templates";
    String fileName = "idlTypes.stg";
    String filePath = relativePath + "/" + fileName;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream res = classLoader.getResourceAsStream(var4);
    if(res == null) {
        classLoader = this.getClass().getClassLoader();
        res = classLoader.getResourceAsStream(var4);
    }

    if(res != null) {
        return new BufferedReader(getInputStreamReader(res));
    }
}

      

The res resource is always null, regardless of relativePath (relative to the project root). I tried using the following paths with the same result:

String relativePath = "src/main/java/com/eprosima/templates";
String relativePath = "src/main/java/com.eprosima/templates";

      

The classpath looks like this:

enter image description here

I need to read the template files located in / src / main / java / com / eprosima / templates .

+3


source to share


2 answers


String relativePath = "/src/main/java/com/eprosima/templates";

      

The problem is here. src/main/java

is not part of your classpath. This is not at all during execution. It should be



String relativePath = "/com/eprosima/templates";

      

+1


source


try it

String relativePath = "./src/main/java/com/eprosima/templates";

      

For example, I have a project with the com.example.main package. In this package I have "FileTest.java" with the following code:

package com.example.main;

      

import java.io.File;



public class FileTest {

/**
 * @param args
 */
public static void main(String[] args) {
    File file = new File("./src/com/example/main/FileTest.java");
    if (file.exists()) {
        System.out.println("existed!");
    } else {
        System.out.println("not exists!");
    }
}

      

}

then run that file. The output prints "existed!"

Hope for this help!

-1


source







All Articles