Java는 여러 줄 문자열을 지원합니까?
Perl에서는 소스 코드에서 여러 줄의 문자열을 작성하는 "여기 문서" 수단을 찾을 수 없습니다.
$string = <<"EOF" # create a three-line string
text
text
text
EOF
자바에서는 여러 줄의 문자열을 처음부터 연결할 때 모든 줄에 따옴표와 플러스 기호를 붙여야 합니다.
더 좋은 대안이 뭐가 있을까요?속성 파일에서 내 문자열을 정의하시겠습니까?
편집: 2개의 답변에 따르면 StringBuilder.append()는 플러스 표기보다 바람직합니다.누가 그들이 왜 그렇게 생각하는지 설명해 줄 수 있나요?내가 보기엔 전혀 더 좋아 보이지 않는다.저는 멀티라인 문자열이 1등급 언어 구조가 아니라는 사실을 회피하는 방법을 찾고 있습니다.즉, 1등급 언어 구조(+와 문자열 연결)를 메서드 호출로 대체하고 싶지 않습니다.
편집: 더 명확하게 하기 위해 퍼포먼스에 대해서는 전혀 신경 쓰지 않습니다.유지 보수성 및 설계상의 문제가 우려됩니다.
메모: 이 답변은 Java 14 이전 버전에 적용됩니다.
텍스트 블록(복수 리터럴)은 Java 15에서 도입되었습니다.상세한 것에 대하여는, 다음의 회답을 참조해 주세요.
Java에는 존재하지 않는 여러 줄의 리터럴을 원하는 것 같습니다.
은 그냥 입니다.+ Builder 'String Builder', ' 빌더, 스트링,String., .【String.join】(String.join) 【String.join】(String.join) 【String.】(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 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() 쓸 도 있어요.%nString.format.
다른 옵션은 리소스를 텍스트 파일에 넣고 해당 파일의 내용을 읽는 것입니다.이 방법은 클래스 파일이 불필요하게 부풀어 오르는 것을 방지하기 위해 매우 큰 문자열에 적합합니다.
만약 당신이 옵션을 켜이클립스에서 그리고multi-lined 문자열을 붙여(기본 설정에 편집기 >, 타이핑 자바>입니다.)내 시세, 자동으로 추가할 것이다 Eclipse에서"때 잘 엮기 위해서 문자 그대로의 붙이기 텍스트에서 탈출하세요"옵션을 켜고([선호]>,[자바]>,[편집기]>,[타이핑]에서 여러 줄의 문자열을 따옴표로 붙여" 때 붙이기 문자열 리터럴에 텍스트에서 탈출하세요". 넣으면 자동으로 추가됩니다." ★★★★★★★★★★★★★★★★★」\n" +당신의 모든 대사들을 위해.
String str = "paste your text here";
Stephen Colebourne은 Java 7에서 여러 줄의 문자열을 추가하는 제안을 만들었습니다.
또한 Groovy는 이미 여러 줄의 줄을 지원합니다.
이것은 오래된 스레드입니다만, 매우 우아한 새로운 솔루션(약 4개 또는 3개의 작은 결점만 있음)은 커스텀 주석을 사용하는 것입니다.
체크: http://www.adrianwalker.org/2011/12/java-multiline-string.html
이 작업에서 영감을 얻은 프로젝트는 GitHub에서 호스팅됩니다.
https://github.com/benelog/multiline
Java 코드의 예:
import org.adrianwalker.multilinestring.Multiline;
...
public final class MultilineStringUsage {
/**
<html>
<head/>
<body>
<p>
Hello<br/>
Multiline<br/>
World<br/>
</p>
</body>
</html>
*/
@Multiline
private static String html;
public static void main(final String[] args) {
System.out.println(html);
}
}
단점은 다음과 같습니다.
- 해당(제공된) 주석 프로세서를 활성화해야 합니다.
- 해당 String 변수를 로컬 변수로 정의할 수 없습니다. 변수를 로컬 변수로 정의할 수 있는 원시 문자열 리터럴 검사 프로젝트
- 에는 VisualBasic과 할 수 없습니다.리터럴을 한 Net(XML 리터럴)
<%= variable %>:-) :-) - 해당 문자열 리터럴은 JavaDoc 코멘트(/**)로 구분됩니다.
또한 Javadoc 코멘트가 자동으로 다시 포맷되지 않도록 Eclipse/Inteli-Idea를 구성해야 할 수도 있습니다.
이상하다고 생각할지도 모르지만(Javadoc 코멘트는 코멘트 이외의 것을 포함하도록 설계되어 있지 않습니다).이러한 자바 문자열의 부족은 결국 매우 귀찮기 때문에, 저는 이것이 가장 나쁜 해결책이라고 생각합니다.
JEP 378: 텍스트 블록은 이 기능을 다루며 JDK 15에 포함되어 있습니다.처음에 JDK 13에서는 JEP 355: 텍스트블록(미리보기)으로, JDK 14에서는 JEP 368: 텍스트블록(두 번째 미리보기)으로 표시되었으며, 이러한 버전에서는 를 사용하여 활성화할 수 있습니다.––enable–previewoption.svvac "svavac "을 클릭합니다.
이 구문을 사용하면 다음과 같은 내용을 쓸 수 있습니다.
String s = """
text
text
text
""";
이 JEP의 이전 버전인 JDK 12에서는 JEP 326: Raw String Literals는 유사한 기능의 구현을 목표로 하고 있었습니다만, 최종적으로 철회되었습니다.
주의:이것은 JDK 12의 미리보기 언어 기능을 의도하고 있었지만 취소되어 JDK 12에는 표시되지 않았습니다.JDK 13에서는 텍스트 블록(JEP 355)으로 대체되었습니다.
다른 옵션은 긴 문자열을 외부 파일에 저장하고 파일을 문자열로 읽는 것입니다.
이것은 여러분이 그것이 무엇을 하고 있는지 생각하지 않고 사용해서는 안 되는 것입니다.그러나 일회성 스크립트의 경우, 저는 이것을 매우 성공적으로 사용했습니다.
예:
System.out.println(S(/*
This is a CRAZY " ' ' " multiline string with all sorts of strange
characters!
*/));
코드:
// From: http://blog.efftinge.de/2008/10/multi-line-string-literals-in-java.html
// Takes a comment (/**/) and turns everything inside the comment to a string that is returned from S()
public static String S() {
StackTraceElement element = new RuntimeException().getStackTrace()[1];
String name = element.getClassName().replace('.', '/') + ".java";
StringBuilder sb = new StringBuilder();
String line = null;
InputStream in = classLoader.getResourceAsStream(name);
String s = convertStreamToString(in, element.getLineNumber());
return s.substring(s.indexOf("/*")+2, s.indexOf("*/"));
}
// From http://www.kodejava.org/examples/266.html
private static String convertStreamToString(InputStream is, int lineNum) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null; int i = 1;
try {
while ((line = reader.readLine()) != null) {
if (i++ >= lineNum) {
sb.append(line + "\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
String.join
은 Java 8에 새로운 했습니다.java.lang.String을 사용하다
String.join( CharSequence delimiter , CharSequence... elements )
사용방법:
String s = String.join(
System.getProperty("line.separator"),
"First line.",
"Second line.",
"The rest.",
"And the last!"
);
Java 13 이상
이제 Java에서 텍스트 블록을 통해 여러 줄 문자열이 지원됩니다.Java 13 및 14에서는 이 기능을 사용하려면––enable–preview옵션을 선택할 수 있습니다.Java 15 이상에서는 텍스트 블록이 표준 기능이 되었기 때문에 이 옵션은 더 이상 필요하지 않습니다.자세한 내용은 공식 프로그래머 텍스트 블록 가이드를 참조하십시오.
Java 13 이전 버전에서는 다음과 같이 쿼리를 작성합니다.
List<Tuple> posts = entityManager
.createNativeQuery(
"SELECT *\n" +
"FROM (\n" +
" SELECT *,\n" +
" dense_rank() OVER (\n" +
" ORDER BY \"p.created_on\", \"p.id\"\n" +
" ) rank\n" +
" FROM (\n" +
" SELECT p.id AS \"p.id\",\n" +
" p.created_on AS \"p.created_on\",\n" +
" p.title AS \"p.title\",\n" +
" pc.id as \"pc.id\",\n" +
" pc.created_on AS \"pc.created_on\",\n" +
" pc.review AS \"pc.review\",\n" +
" pc.post_id AS \"pc.post_id\"\n" +
" FROM post p\n" +
" LEFT JOIN post_comment pc ON p.id = pc.post_id\n" +
" WHERE p.title LIKE :titlePattern\n" +
" ORDER BY p.created_on\n" +
" ) p_pc\n" +
") p_pc_r\n" +
"WHERE p_pc_r.rank <= :rank\n",
Tuple.class)
.setParameter("titlePattern", "High-Performance Java Persistence %")
.setParameter("rank", 5)
.getResultList();
Java 13 텍스트블록 덕분에 이 쿼리를 다음과 같이 다시 작성할 수 있습니다.
List<Tuple> posts = entityManager
.createNativeQuery("""
SELECT *
FROM (
SELECT *,
dense_rank() OVER (
ORDER BY "p.created_on", "p.id"
) rank
FROM (
SELECT p.id AS "p.id",
p.created_on AS "p.created_on",
p.title AS "p.title",
pc.id as "pc.id",
pc.created_on AS "pc.created_on",
pc.review AS "pc.review",
pc.post_id AS "pc.post_id"
FROM post p
LEFT JOIN post_comment pc ON p.id = pc.post_id
WHERE p.title LIKE :titlePattern
ORDER BY p.created_on
) p_pc
) p_pc_r
WHERE p_pc_r.rank <= :rank
""",
Tuple.class)
.setParameter("titlePattern", "High-Performance Java Persistence %")
.setParameter("rank", 5)
.getResultList();
훨씬 더 읽기 쉽죠?
IDE 지원
는 레거시 IntelliJ IDEA의 합니다.String String★★★★
JSON, HTML, XML
'''String JSON,, XML의 에 특히 편리합니다.
에서는 ''를 사용해서 생각해 보세요.StringJSON:
entityManager.persist(
new Book()
.setId(1L)
.setIsbn("978-9730228236")
.setProperties(
"{" +
" \"title\": \"High-Performance Java Persistence\"," +
" \"author\": \"Vlad Mihalcea\"," +
" \"publisher\": \"Amazon\"," +
" \"price\": 44.99," +
" \"reviews\": [" +
" {" +
" \"reviewer\": \"Cristiano\", " +
" \"review\": \"Excellent book to understand Java Persistence\", " +
" \"date\": \"2017-11-14\", " +
" \"rating\": 5" +
" }," +
" {" +
" \"reviewer\": \"T.W\", " +
" \"review\": \"The best JPA ORM book out there\", " +
" \"date\": \"2019-01-27\", " +
" \"rating\": 5" +
" }," +
" {" +
" \"reviewer\": \"Shaikh\", " +
" \"review\": \"The most informative book\", " +
" \"date\": \"2016-12-24\", " +
" \"rating\": 4" +
" }" +
" ]" +
"}"
)
);
JSON은 문자가 빠져나와 큰따옴표와 플러스 기호가 풍부하기 때문에 거의 읽을 수 없습니다.
Java Text Blocks에서는 JSON 오브젝트를 다음과 같이 쓸 수 있습니다.
entityManager.persist(
new Book()
.setId(1L)
.setIsbn("978-9730228236")
.setProperties("""
{
"title": "High-Performance Java Persistence",
"author": "Vlad Mihalcea",
"publisher": "Amazon",
"price": 44.99,
"reviews": [
{
"reviewer": "Cristiano",
"review": "Excellent book to understand Java Persistence",
"date": "2017-11-14",
"rating": 5
},
{
"reviewer": "T.W",
"review": "The best JPA ORM book out there",
"date": "2019-01-27",
"rating": 5
},
{
"reviewer": "Shaikh",
"review": "The most informative book",
"date": "2016-12-24",
"rating": 4
}
]
}
"""
)
);
2004년에 C#를 사용한 이래, Java에서 이 기능을 사용하고 싶다고 생각하고 있었습니다만, 드디어 이 기능을 사용할 수 있게 되었습니다.
속성 파일에서 문자열을 정의하면 훨씬 더 나빠집니다.IIRC는 다음과 같습니다.
string:text\u000atext\u000atext\u000a
일반적으로 소스에 큰 문자열을 삽입하지 않는 것이 합리적입니다.XML 또는 읽기 쉬운 텍스트 형식으로 리소스로서 로드할 수 있습니다.텍스트 파일은 런타임에 읽거나 Java 소스로 컴파일할 수 있습니다. 그, 는 그 소스에 .+「 」 「 」 、 「 」 、 「 」 。
final String text = ""
+"text "
+"text "
+"text"
;
새로운 행이 있는 경우는, Join 또는 포맷 방식을 사용할 수 있습니다.
final String text = join("\r\n"
,"text"
,"text"
,"text"
);
플러스는 StringBuilder.append로 변환됩니다.단, 컴파일러가 컴파일 시에 그것들을 조합할 수 있도록 양쪽 문자열이 상수인 경우는 제외합니다.적어도 Sun의 컴파일러에서는 그렇게 되어 있습니다.다른 컴파일러들도 다 똑같지는 않겠지만 대부분의 컴파일러는 그렇게 되어 있을 것입니다.
그래서:
String a="Hello";
String b="Goodbye";
String c=a+b;
는 보통 다음과 같은 코드를 생성합니다.
String a="Hello";
String b="Goodbye":
StringBuilder temp=new StringBuilder();
temp.append(a).append(b);
String c=temp.toString();
한편, 다음과 같습니다.
String c="Hello"+"Goodbye";
다음과 같습니다.
String c="HelloGoodbye";
즉, 문자열 리터럴을 여러 줄에 걸쳐 읽기 쉽도록 플러스 기호로 구분해도 아무런 불이익이 없습니다.
IntelliJ IDE에서 다음과 같이 입력하면 됩니다.
""
그런 다음 따옴표 안에 커서를 놓고 문자열을 붙여넣습니다.IDE 는, 복수의 연결 행으로 전개합니다.
안타깝게도 Java에는 여러 줄의 문자열 리터럴이 없습니다.문자열 리터럴을 연결하거나(+ 또는 String Builder를 사용하여) 별도의 파일에서 문자열을 읽어야 합니다.
의 경우 에서 읽을 수 getResourceAsStream())Class 인스톨 되고 있는 가 없기 에, 수 있습니다.따라서 현재 디렉토리와 코드가 설치된 위치에 대해 걱정할 필요가 없으므로 파일을 쉽게 찾을 수 있습니다.또한 파일을 jar 파일에 저장할 수 있기 때문에 패키징이 더 쉬워집니다.
네가 푸라는 반에 있다고 가정해봐.다음과 같은 작업을 수행합니다.
Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);
또 다른 골칫거리는 자바에는 표준적인 "이 리더의 모든 텍스트를 문자열로 읽는다" 방법이 없다는 것입니다.그래도 꽤 쉽게 쓸 수 있습니다.
public static String readAll(Reader input) {
StringBuilder sb = new StringBuilder();
char[] buffer = new char[4096];
int charsRead;
while ((charsRead = input.read(buffer)) >= 0) {
sb.append(buffer, 0, charsRead);
}
input.close();
return sb.toString();
}
String newline = System.getProperty ("line.separator");
string1 + newline + string2 + newline + string3
String multilineString = String.format("%s\n%s\n%s\n",line1,line2,line3);
Java는 (아직) 네이티브로 멀티라인 스트링을 지원하지 않기 때문에, 현재 유일한 방법은 앞서 말한 기술 중 하나를 사용하여 해킹하는 것입니다.위에서 언급한 몇 가지 트릭을 사용하여 다음과 같은 Python 스크립트를 구축했습니다.
import sys
import string
import os
print 'new String('
for line in sys.stdin:
one = string.replace(line, '"', '\\"').rstrip(os.linesep)
print ' + "' + one + ' "'
print ')'
그것을 javastringify.py 라는 파일에 넣고 당신의 문자열을 mystring 파일에 넣습니다.txt를 실행하여 다음과 같이 실행합니다.
cat mystring.txt | python javastringify.py
그런 다음 출력을 복사하여 편집기에 붙여넣을 수 있습니다.
필요에 따라 수정하여 특별한 경우를 처리해 주십시오.하지만, 이것은 제 요구에 부합합니다.이게 도움이 됐으면 좋겠네요!
scala-code를 사용할 수 있습니다.이 코드는 Java와 호환되며 "로 둘러싸인 여러 줄 스트링을 허용합니다.
package foobar
object SWrap {
def bar = """John said: "This is
a test
a bloody test,
my dear." and closed the door."""
}
(문자열 안쪽 따옴표 참조) 및 Java:
String s2 = foobar.SWrap.bar ();
이게 더 편한지...?
소스 코드에 배치해야 하는 긴 텍스트를 처리하는 경우가 많은 경우에는 외부 파일에서 텍스트를 가져와 다음과 같이 multiline-java-String으로 래핑하는 스크립트를 사용할 수 있습니다.
sed '1s/^/String s = \"/;2,$s/^/\t+ "/;2,$s/$/"/' file > file.java
쉽게 잘라낼 수 있습니다.
실제로, 이하가 지금까지 본 것 중 가장 깨끗한 실장입니다.주석을 사용하여 주석을 문자열 변수로 변환합니다.
/**
<html>
<head/>
<body>
<p>
Hello<br/>
Multiline<br/>
World<br/>
</p>
</body>
</html>
*/
@Multiline
private static String html;
따라서 최종 결과는 변수 html에 여러 줄의 문자열이 포함됩니다.따옴표, 플러스, 쉼표 없이 순수 문자열만 사용할 수 있습니다.
이 솔루션은 다음 URL에서 이용할 수 있습니다.http://www.adrianwalker.org/2011/12/java-multiline-string.html
도움이 됐으면 좋겠네요!
Java Stringfier 를 참조해 주세요.필요에 따라 텍스트를 String Builder Java 블록 이스케이프로 변환합니다.
다음과 같은 다른 방법으로 추가를 연결할 수 있습니다.
public static String multilineString(String... lines){
StringBuilder sb = new StringBuilder();
for(String s : lines){
sb.append(s);
sb.append ('\n');
}
return sb.toString();
}
쪽이든, ★★★★★★★★★★★★★★★★★★★★★★★★.StringBuilder+ 표기로 변환합니다.
import org.apache.commons.lang3.StringUtils;
String multiline = StringUtils.join(new String[] {
"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",
}, "\n");
제가 아직 답변으로 보지 못한 대안은 입니다.
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
writer.println("It was the best of times, it was the worst of times");
writer.println("it was the age of wisdom, it was the age of foolishness,");
writer.println("it was the epoch of belief, it was the epoch of incredulity,");
writer.println("it was the season of Light, it was the season of Darkness,");
writer.println("it was the spring of hope, it was the winter of despair,");
writer.println("we had everything before us, we had nothing before us");
String string = stringWriter.toString();
또, 가 가지고 있는 것은,newLine()방법은 기재되어 있지 않습니다.
Java 13 미리보기:
텍스트 블록 Java로 이동합니다.Java 13은 Mala Gupta가 오랫동안 기다려온 멀티라인 스트링을 제공합니다.
텍스트 블록에서는 Java 13을 사용하여 여러 줄의 문자열 리터럴을 쉽게 사용할 수 있습니다.문자열 리터럴의 특수 문자를 이스케이프하거나 여러 줄에 걸친 값에 연결 연산자를 사용할 필요가 없습니다.
텍스트 블록은 3개의 큰따옴표("")를 사용하여 시작 및 종료 구분자로 정의됩니다.선두 딜리미터 뒤에는 0 이상의 공백과 줄 끝자를 사용할 수 있습니다.
예:
String s1 = """
text
text
text
""";
JDK/12 얼리 액세스빌드 #12에서는 다음과 같이 Java에서 여러 줄의 문자열을 사용할 수 있습니다.
String multiLine = `First line
Second line with indentation
Third line
and so on...`; // the formatting as desired
System.out.println(multiLine);
그 결과, 다음과 같은 출력이 됩니다.
First line Second line with indentation Third line and so on...
편집: Java 13으로 연기
매우 효율적이고 플랫폼에 의존하지 않는 솔루션에서는 시스템속성을 사용하여 행 구분자와 String Builder 클래스를 사용하여 문자열을 작성합니다.
String separator = System.getProperty("line.separator");
String[] lines = {"Line 1", "Line 2" /*, ... */};
StringBuilder builder = new StringBuilder(lines[0]);
for (int i = 1; i < lines.length(); i++) {
builder.append(separator).append(lines[i]);
}
String multiLine = builder.toString();
Properties.loadFromXML(InputStream) 립은 외부 립은 필요 없습니다.
복잡한 코드보다(유지관리성과 설계가 중요하므로) 긴 문자열을 사용하지 않는 것이 좋습니다.
xml xml 을 .
InputStream fileIS = YourClass.class.getResourceAsStream("MultiLine.xml");
Properties prop = new Properies();
prop.loadFromXML(fileIS);
여러 줄의 스트링을 좀 더 유지 보수적으로 사용할 수 있습니다.
static final String UNIQUE_MEANINGFUL_KEY = "Super Duper UNIQUE Key";
prop.getProperty(UNIQUE_MEANINGFUL_KEY) // "\n MEGA\n LONG\n..."
MultiLine.xml'을 선택합니다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="Super Duper UNIQUE Key">
MEGA
LONG
MULTILINE
</entry>
</properties>
★★★를 사용할 수 있습니다.<![CDATA[""]]>를 지정합니다.
만약 당신이 나만큼 구글의 guava를 좋아한다면, 그것은 꽤 깔끔한 표현을 제공할 수 있고, 당신의 새로운 글자를 하드코드하지 않는 멋지고 쉬운 방법을 줄 수 있다.
String out = Joiner.on(newline).join(ImmutableList.of(
"line1",
"line2",
"line3"));
한 가지 좋은 선택지.
import static some.Util.*;
public class Java {
public static void main(String[] args) {
String sql = $(
"Select * from java",
"join some on ",
"group by"
);
System.out.println(sql);
}
}
public class Util {
public static String $(String ...sql){
return String.join(System.getProperty("line.separator"),sql);
}
}
속성 파일에서 내 문자열을 정의하시겠습니까?
속성 파일에는 여러 줄 문자열이 허용되지 않습니다.속성 파일에는 \n을 사용할 수 있지만, 고객님의 경우는 그다지 해결 방법이 아니라고 생각합니다.
오래된 질문인 건 알지만, 관심 있는 개발자들에게는 #Java12에 여러 라인 리터럴이 포함될 예정입니다.
http://mail.openjdk.java.net/pipermail/amber-dev/2018-July/003254.html
ThomasP가 제안한 유틸리티를 사용하여 빌드 프로세스에 링크하는 것이 좋습니다.텍스트를 포함하는 외부 파일이 아직 있지만 실행 시 파일을 읽을 수 없습니다.워크플로우는 다음과 같습니다.
- 'textfile to java code' 유틸리티 구축 및 버전 관리 체크 인
- 빌드마다 리소스 파일에 대해 유틸리티를 실행하여 수정된 Java 소스를 만듭니다.
- 에는 Java Source와 같은 되어 있습니다.
class TextBlock {...문자열이 됩니다. - 생성된 Java 파일을 나머지 코드와 함께 빌드합니다.
언급URL : https://stackoverflow.com/questions/878573/does-java-have-support-for-multiline-strings
'source' 카테고리의 다른 글
| 루트 인스턴스를 인스턴스화하지 않고 vue 구성 요소를 사용하는 방법은 무엇입니까? (0) | 2022.08.18 |
|---|---|
| Vue.js: Vuex 액션에서 실현되지 않은 약속 (0) | 2022.08.18 |
| 공유 호스팅에 larabel + vuej 도입 (0) | 2022.08.18 |
| 부호 있는 문자와 부호 없는 문자의 차이 (0) | 2022.08.18 |
| 경고: 문자열 리터럴과 비교하면 지정되지 않은 동작이 발생합니다. (0) | 2022.08.18 |
