Get system resource inside Jar file (getSystemResource)

2

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

I tried 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 ran the following line at the command prompt: java -cp myProject.jar; lib / *; project.entry.point.App

and got the following error

Ithinktheproblemisfindingthepathofafile,I'mdoingit:ClassLoader.getSystemResource("resources/CREATE_DB.sql");
but as you can see there in the image in the error that after the name of the .jar is the character '!' I do not understand why

Any ideas how to solve the problem?

    
asked by anonymous 22.06.2014 / 19:41

1 answer

1

I had a similar problem and in this case I recommend that you use this.getClass().getResourceAsStream("") to handle it smoothly.

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 there will be no errors when running in an IDE (Netbeans / Eclipse) but the first two settings will not run directly if I start the Jar only i.e.

java -jar StackOverflow.jar

If you want to download the project, you can find it at GitHub

    
22.06.2014 / 23:06