Can Class.getResource () only be able to recover files in internal folders that the class is in?

0

In this class, I need to read *.properties files that are in another folder / project package. The folder structure is this:

  

util → properties (here are the .properties)

     

util → server → queries (here is the class that will read the .properties)

package util.server.consultas;
import java.io.File;
import org.restlet.Response;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class ConsultasResource extends ServerResource {

  @Get
  public Response returnConsulta() throws Exception {
    File dir = new File(getClass().getResource(/*Como proceder aqui?*/"").toExternalForm());
    return getResponse();
  }
}

Is there any way that this method can work if I extract the file to .jar?

    
asked by anonymous 05.12.2014 / 18:52

2 answers

0

I was able to solve it here, follow the code:

package util.server.consultas;

import java.io.File;
import java.io.FileReader;

import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class ConsultasResource extends ServerResource {

  @Get
  public Response returnConsultas() throws Exception {
    Response response = getResponse();
    StringBuilder sb = new StringBuilder();
    File dir = new File("C:/Users/<usuario>/workspace/projeto/src/util/properties/consultas");
    File[] files = dir.listFiles();
    File arq = null;
    for(int i = 0; i<files.length; i++) {
        arq = files[i];
        FileReader reader = new FileReader(arq);
        while(reader.ready()) {
            sb.append(Character.toChars(reader.read()));
        }
        reader.close();
    };
    response.setEntity(sb.toString(), MediaType.TEXT_PLAIN);
    return response;
  }
}

This takes text from all .properties files in the Queries folder.

    
08.12.2014 / 14:27
0

When you do:

getClass().getResource()

It will consider the class package (relative path from the class).

When you do:

getClass().getClassLoader().getResource()

It will consider the root of the ClassLoader (absolute path from the classLoader).

So these are equivalent for you:

util.server.consultas.SuaClasse.class.getResource("/util/properties/bla.properties");
util.server.consultas.SuaClasse.class.getClassLoader().getResource("util/properties/bla.properties");

removed from English OS

Are you using JAX-RS?

I noticed the imports. If you want to return a resource from within your WAR (from the webapp folder), inject the ServletContext into your endPoint by putting a property in your servlet:

@javax.ws.rs.core.Context 
private ServletContext context;

and do:

servletContext.getResource("/...");
    
06.12.2014 / 01:24