Get system resource within Jar file (getSystemResource)

Asked

Viewed 772 times

2

I developed a project where I need to access some configuration files and some images. Inside the project I have a folder (Resources) in which I have all these resources I need.
The problem is this:
After the finished project I created a jar and inside it is the whole code and the resouces folder.

I went to try to run the program in a directory where I only have two things:
1 folder (lib) where I have other jar I need
1 . jar with my project

I executed in command prompt the following line: java -cp myProject.jar;lib/*; project.entry.point.App

and got the following error inserir a descrição da imagem aqui

I think the problem is finding the path of a file, I’m doing: ClassLoader.getSystemResource("resources/CREATE_DB.sql");
but as you can see there in the image in the error that gives after the name of . jar is the character '!' I don’t understand why

Any idea how to solve the problem?

  • Try to put the folder resources in the same directory as the jar, and run again and see if the problem persists.

  • Kyllopardiun thanks for the answer, yes before asking the question I did it and it worked but supposedly the folder is inside the . there should be a way to do it without having the resouces folder in the current directory

1 answer

1

I had a similar problem and in this case I recommend using this.getClass().getResourceAsStream("") to be able to manipulate without problems.

Example

stack.Config.java:

package stack;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

public class Config {
    private String usuario;
    private String db;
    private String website;
    private String path;
    public void setConfigPorStream(boolean flag){
        try{
            InputStream is; 
           if(flag){
                 // stack.res/conf.txt
                 is =  this.getClass().getResourceAsStream("res/conf.txt");
           }
           else{
                 //res/conf.txt
                 is = ClassLoader.getSystemResourceAsStream("res/conf.txt");
           }
            //O tamanho do arquivo provavelmente será o mesmo sempre
            // e por isso BufferedReader é desnecessário.
           byte[] b = new byte[1024];
            is.read(b);
            String config = new String(b,"UTF-8");
            this.db = parseConfig(config, "dbUrl");
            this.website = parseConfig(config, "website");
            this.usuario = parseConfig(config, "usuario");
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void setConfig_PastadoJar(boolean flag) {
        URL arquivo;
        if(flag)
            arquivo = ClassLoader.getSystemResource("res/conf.txt");
        else{
            arquivo = this.getClass().getResource("res/conf.txt");
        }        
        FileInputStream fis  = null;
        try {
            fis = new FileInputStream(arquivo.getFile());
            byte[] b = new byte[1024];
            fis.read(b);
            String config = new String(b,"UTF-8");
            this.db = parseConfig(config, "dbUrl");
            this.website = parseConfig(config, "website");
            this.usuario = parseConfig(config, "usuario");
            } catch (Exception e) {
               e.printStackTrace();
            }
        }
        public String getUsuario(){
            return this.usuario;
        }
        public String getDB(){
            return this.db;
        }
        public String getWebsite(){
            return this.website;
        }
    public static String parseConfig(String linha,String campo){
        linha = linha.replaceAll("\"","");
        int indice = linha.indexOf(campo) + 3 + campo.length();
        int ultimo_char = linha.indexOf(",", indice)!=-1?linha.indexOf(",", indice):linha.indexOf("}", indice);
        return linha.substring(indice,ultimo_char);
    }
}

stack.Stackoverflow

package stack;
public class StackOverflow{

    public static void main(String[] args) {
            Config conf = new Config();
            System.out.println("-----------------------\n\tPasta onde está o jar\n-----------------------\n");
            conf.setConfig_PastadoJar(true);
            printConfig(conf);
            System.out.println("");
            conf.setConfig_PastadoJar(false);
            printConfig(conf);
            System.out.println("-----------------------\n\tDentro do jar\n-----------------------\n");
            conf.setConfigPorStream(false);
            System.out.println("StackOverflow.jar\\!res\\conf.txt");
            printConfig(conf);
            System.out.println("");
            System.out.println("StackOverflow.jar\\!stack\\res\\conf.txt");
            conf.setConfigPorStream(true);
            printConfig(conf);
        }
        public static void printConfig(Config c){
            System.out.println("Usuario: " + c.getUsuario());
            System.out.println("DB: " + c.getDB());
            System.out.println("Website: " + c.getWebsite());
        }
        


}

res.conf.txt && res stack..conf.txt

{eg{usuario = "dbAdmin", dbUrl = "http://db.pt.stackoverflow.com", website = "pt.StackOverflow"}}

Note that in this example you will not have errors running in an IDE (Netbeans/Eclipse) but the first two settings will not run directly if you start only Jar i.e.

java -jar StackOverflow.jar

If you want to download the project, you can find it on Github

Browser other questions tagged

You are not signed in. Login or sign up in order to post.