0

I am trying to read a text file to my servlet. I thought this statement,

String context = getServletContext().getRealPath("/WEB-INF/rates.txt");

would give me a string of the file contents. My question is: How can I retrieve the file contents into a string?
Here is my code:

public void init( ServletConfig config ) throws ServletException
{
    super.init( config );

    String context = getServletContext().getRealPath("/WEB-INF/rates.txt");
    ArrayList<CurrencyRate> CR = new ArrayList<CurrencyRate>();

    String[] temp = context.split(",\\s*");

    for(int i =0; i < temp.length -1; i+=2 ) {
        CR.add(new CurrencyRate(temp[i], Double.parseDouble(temp[i+1])));
    }

    getServletContext().setAttribute( "CR", CR );
}
Abra
  • 19,142
  • 7
  • 29
  • 41
Jay F
  • 13
  • 1

1 Answers1

0

You can use Files.readAllBytes method. You can find a demo here. Note that your context variable is actually the file path, not the file contents.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43