如何在Java servlet中读取文件

问题描述 投票:0回答:1

我想将文本文件读取到我认为的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 );
}
java file servlets text readfile
1个回答
0
投票

您可以使用Files.readAllBytes方法。您可以找到一个演示here。请注意,您的上下文变量实际上是文件路径,而不是文件内容。

© www.soinside.com 2019 - 2024. All rights reserved.