Звучит так, будто вы хотите создать многострочный литерал, которого нет в 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.getProperty("line.separator")
, либо вы можете использовать %n
в String.format
.
Другой вариант - поместить ресурс в текстовый файл и просто прочитать содержимое этого файла. Это было бы предпочтительным для очень больших строк, чтобы избежать ненужного раздувания ваших файлов классов.