在Web应用程序中以字符串形式读取src / main / resources中的文件的正确方法? [英] Correct way of reading a file in src/main/resources as string in a web application?

查看:83
本文介绍了在Web应用程序中以字符串形式读取src / main / resources中的文件的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,它具有以下结构(部分)。

I have a web application which has following structure (partial).

Project Name
   src/main/java
       com.package
           MainFile.java
   src/main/resources
       sample.xml

现在我想从MainFile.java中读取sample.xml作为字符串。

Now I want to read sample.xml from MainFile.java as a string.

我尝试使用此方法但得到 NoSuchFileException

I tried using this method but got NoSuchFileException

byte[] encoded = Files.readAllBytes(Paths.get("src/main/resources/sample.xml"));
return new String(encoded, StandardCharsets.UTF_8);

请提出解决此问题的方法。

Please suggest a solution to this issue.

推荐答案

此文件位于Web应用程序类路径中,因此您可以这样:

This file is in the web app classpath, so you can get it like:

Path path = Paths.get(getClass().getResource("/sample.xml").toURI());
return new String(Files.readAllBytes(path));

这篇关于在Web应用程序中以字符串形式读取src / main / resources中的文件的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆