Class.getResource() can only recover files in internal folders to which the class is located?

Asked

Viewed 4,028 times

0

In this class, I need to read files *.properties that are in another project folder/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();
  }
}

And there is the possibility that this method might work if I extract the file to . jar?

2 answers

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 Classloader root (absolute path from classLoader).

So these here are equivalent to you:

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

out of the English OS

You’re using JAX-RS ?

I noticed it on the Imports. If you want to return a resource from within your WAR (from the webapp folder), insert Servletcontext into your endpoint by placing a property in your Servletlet:

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

and make:

servletContext.getResource("/...");
  • I’m using the Restlet library. It’s kind of similar.

0


I managed to solve 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 the text of all the . properties files from the Queries folder.

Browser other questions tagged

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