By using ServletContext, We can get WebContent and WebInf folder paths. Here the trick is getting ServletContext in Restful web service. Find below example program
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;

@Path("readContent")
public class ContentResource {
/*
 * this class is for reading file content
 * REST Full web services
 */
    
    /*
     * This method is for reading files in WebContent
     * @return String
     */
    @GET
    @Path("webcontent")
    public String readWebContentFile(@Context ServletContext context, @QueryParam("file") String fileName){
        String fullPath = context.getRealPath("/"+fileName);
        return readTextFromFile(fullPath);
    }

    /*
     * This method is for reading files in WEB-INF folder
     * @return String
     */
    @GET
    @Path("webinf")
    public String readWebInfFile(@Context ServletContext context,@QueryParam("file") String fileName) {
        String fullPath = context.getRealPath("/WEB-INF/"+fileName);
        return readTextFromFile(fullPath);
    }
    
    /*
     * Read text from file
     * @param fileName
     * @return String
     */
    public String readTextFromFile(String fileName) {
        String result = null;
        String line = null;
        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            String text = "";
            while((line = bufferedReader.readLine()) != null) {
                text += "\n"+line;
            }   

            result = text;
            // Always close files.
            bufferedReader.close();
        }
        catch(FileNotFoundException ex) {
            result = "Unable to open file";                
        }
        catch(IOException ex) {
            result = "Error reading file";
        }
        return result;
    }
}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts