Sebi
Sebi

Reputation: 4522

Obtaining an input stream from a classpath file

After reading this question, I have tried the following when 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 resource res is always null regardless of the relativePath(relative to the project root directory). I have tried to use the following paths with the same outcome:

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

The classpath looks like:

enter image description here

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

Upvotes: 3

Views: 827

Answers (2)

congtuyenvip
congtuyenvip

Reputation: 44

Try this

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

For example I have project that has package com.example.main. In that package I have "FileTest.java" with 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 this file output prints "existed!"

Hope this help!

Upvotes: -1

user207421
user207421

Reputation: 310869

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

The problem is here. src/main/java is not part of your classpath. It's not there in any way at runtime. It should be

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

Upvotes: 1

Related Questions