【问题标题】:How to read file in java servlet [duplicate]如何在java servlet中读取文件[重复]
【发布时间】:2023-04-01 03:11:02
【问题描述】:

我正在尝试将文本文件读取到我的 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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      • 2016-02-02
      • 1970-01-01
      • 2014-05-21
      • 2018-01-11
      • 1970-01-01
      • 2014-09-05
      相关资源
      最近更新 更多