Java 多行字符串


#Java 笔记


方式1

String s = "床前明月光,\n" +
        "疑是地上霜。\n" +
        "举头望明月,\n" +
        "低头思故乡。";
System.out.println(s);

方式2

StringBuilder sb = new StringBuilder();
sb.append("床前明月光,\n");
sb.append("疑是地上霜。\n");
sb.append("举头望明月,\n");
sb.append("低头思故乡。");
System.out.println(sb.toString());

或者:

StringBuilder sb = new StringBuilder();
sb.append("床前明月光,\n")
  .append("疑是地上霜。\n")
  .append("举头望明月,\n")
  .append("低头思故乡。");
System.out.println(sb.toString());

方式3

public static String join(String delimiter, String ...elements) {
    if (elements.length == 0) {
        return null;
    } else if (elements.length == 1) {
        return elements[0];
    } else {
        StringBuilder sb = new StringBuilder(1024);
        for (int i=0; i < elements.length; ++i) {
            if (i < elements.length-1) {
                sb.append(elements[i]).append(delimiter);
            } else {
                sb.append(elements[i]);
            }

        }
        return sb.toString();
    }
}

public static String multiLines(String ...lines) {
    return join("\n", lines);
}

@Test
public void test() {
    String s = multiLines(
            "床前明月光,",
            "疑是地上霜。",
            "举头望明月,",
            "低头思故乡。"
    );
    System.out.println(s);
}

方式4

将文本写入src/main/resources/constant/jingyesi.txt

床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。

代码:

public String readResource(String path) throws IOException {

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // 符合要求的文件可能不止一个
    Enumeration<URL> configs = ClassLoader.getSystemResources(path);

    List<URL> urlList = new ArrayList<>();

    while(configs.hasMoreElements()) {
        URL url = configs.nextElement();
        urlList.add(url);
    }
    if (urlList.size() != 1) {
        throw new IOException("文件不存在,或者存在重复文件");
    }

    InputStream in = urlList.get(0).openStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));

    StringBuilder sb = new StringBuilder();
    while(true) {
        String line = reader.readLine();
        if (line != null) {
            sb.append(line).append("\n");
        } else {
            break;
        }
    }

    return sb.toString();
}

@Test
public void test() throws IOException {
    System.out.println(readResource("constant/jingyesi.txt"));
}


( 本文完 )