我正在尝试将文本文件读取到我的 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 。请注意,您的上下文变量实际上是文件路径,而不是文件内容。
关于java - 如何在java servlet中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58185066/