Java multiline string

前端 未结 30 3010
醉梦人生
醉梦人生 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:33

    This is something that you should never use without thinking about what it's doing. But for one-off scripts I've used this with great success:

    Example:

        System.out.println(S(/*
    This is a CRAZY " ' ' " multiline string with all sorts of strange 
       characters!
    */));
    

    Code:

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

提交回复
热议问题