注:この回答は、Java14以前に適用されます。
テキストブロック(複数行リテラル)はJava 15で導入されました。詳細については、この回答を参照してください。
Javaには存在しない複数行のリテラルを実行したいようです。
あなたの最良の選択肢は、一緒にされたばかり+
の文字列になるでしょう。人々が言及している他のいくつかのオプション(StringBuilder、String.format、String.join)は、文字列の配列から始めた場合にのみ望ましいでしょう。
このことを考慮:
String s = "It was the best of times, it was the worst of times,\n"
+ "it was the age of wisdom, it was the age of foolishness,\n"
+ "it was the epoch of belief, it was the epoch of incredulity,\n"
+ "it was the season of Light, it was the season of Darkness,\n"
+ "it was the spring of hope, it was the winter of despair,\n"
+ "we had everything before us, we had nothing before us";
対StringBuilder
:
String s = new StringBuilder()
.append("It was the best of times, it was the worst of times,\n")
.append("it was the age of wisdom, it was the age of foolishness,\n")
.append("it was the epoch of belief, it was the epoch of incredulity,\n")
.append("it was the season of Light, it was the season of Darkness,\n")
.append("it was the spring of hope, it was the winter of despair,\n")
.append("we had everything before us, we had nothing before us")
.toString();
対String.format()
:
String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
, "It was the best of times, it was the worst of times,"
, "it was the age of wisdom, it was the age of foolishness,"
, "it was the epoch of belief, it was the epoch of incredulity,"
, "it was the season of Light, it was the season of Darkness,"
, "it was the spring of hope, it was the winter of despair,"
, "we had everything before us, we had nothing before us"
);
対Java8 String.join()
:
String s = String.join("\n"
, "It was the best of times, it was the worst of times,"
, "it was the age of wisdom, it was the age of foolishness,"
, "it was the epoch of belief, it was the epoch of incredulity,"
, "it was the season of Light, it was the season of Darkness,"
, "it was the spring of hope, it was the winter of despair,"
, "we had everything before us, we had nothing before us"
);
特定のシステムの改行が必要な場合は、を使用するか、でを使用できSystem.lineSeparator()
ます。%n
String.format
もう1つのオプションは、リソースをテキストファイルに入れて、そのファイルの内容を読み取ることです。これは、クラスファイルが不必要に肥大化するのを防ぐために、非常に大きな文字列に適しています。