0

ファイルの内容から文字列を作成したい。この答えによると、私はこのようにします:

private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(stringTemplatePath));
    return new String(encoded, "UTF-8");
}

(私が理解しているように、これは Java 7 の一部である新しい NIO2 API のパスです。)

stringTemplatePathパラメーターは、ファイルの名前 ( "template.html" ) です。このファイルの場所を確認します。クラスパスにあります: ../classes/template.html

この関数を呼び出した後、例外が発生します。

java.nio.file.NoSuchFileException: template.html

ファイル名パラメータを間違った方法で送信したのではないでしょうか? この変更を送信しようとしました: "file:///template.html"および"classpath:template.html"ですが、役に立ちませんでした。

また、私はこのコードを試しました:

private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
    File file = new File(stringTemplatePath);
    String absolutePath = file.getAbsolutePath();
    byte[] encoded = Files.readAllBytes(Paths.get(absolutePath));
    return new String(encoded, "UTF-8");
}

この関数を呼び出したところ、次の例外が発生しました。

java.nio.file.NoSuchFileException: /opt/repo/versions/8.0.9/temp/template.html

new File(stringTemplatePath)はファイルを作成できるため、クラスパスにファイルします。しかし、このファイルには非常に奇妙なパス ( /opt/repo/versions/8.0.9/temp/template.html ) があります。私はホスティングとして Jelastic を使用しています (環境: Java 8、Tomcat 8)。


更新: 最終作業ソリューション:

private static String buildStringFromTemplate(String stringTemplatePath) throws IOException {
    InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream(stringTemplatePath);
    return IOUtils.toString(inputStream, "UTF-8"); 
}

IOUtilsは Apache IO Commons の util クラスです。

重要な注意:

classから.getResourceAsStream(...)を呼び出すだけでは、リソース ファイルが見つからず、メソッドはnullを返します。

MyClass.class.getResourceAsStream(stringTemplatePath);

したがって、.getResourceAsStream(...)を呼び出す前に.getClassLoader()を呼び出すと、完全に機能します。

MyClass.class.getClassLoader().getResourceAsStream(stringTemplatePath);
4

2 に答える 2