Java multiline string

前端 未结 30 2959
醉梦人生
醉梦人生 2020-11-22 15:55

Coming from Perl, I sure am missing the \"here-document\" means of creating a multi-line string in source code:

$string = <<\"EOF\"  # create a three-l         


        
30条回答
  •  庸人自扰
    2020-11-22 16:38

    Sadly, Java does not have multi-line string literals. You either have to concatenate string literals (using + or StringBuilder being the two most common approaches to this) or read the string in from a separate file.

    For large multi-line string literals I'd be inclined to use a separate file and read it in using getResourceAsStream() (a method of the Class class). This makes it easy to find the file as you don't have to worry about the current directory versus where your code was installed. It also makes packaging easier, because you can actually store the file in your jar file.

    Suppose you're in a class called Foo. Just do something like this:

    Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
    String s = Utils.readAll(r);
    

    The one other annoyance is that Java doesn't have a standard "read all of the text from this Reader into a String" method. It's pretty easy to write though:

    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();
    }
    

提交回复
热议问题