我想将文本文件读取到我认为的servlet中
String context = getServletContext()。getRealPath(“ / WEB-INF / rates.txt”);
将给我一个文件内容的字符串,我的问题是如何将文件内容检索为一个字符串。这是我的代码:
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 );
}
您可以使用Files.readAllBytes方法。您可以找到一个演示here。请注意,您的上下文变量实际上是文件路径,而不是文件内容。