简体   繁体   中英

How to print a String in multiline Output Java

First of all I'd like to state that, despite the title, this question is not a duplicate of the one I found here: Java multiline string . I read with attention all answers to that question and couldn't find a solution to my problem.

The fundamental difference between my problem and the one of the other question is that I need to print in multiple lines a string of which I do not now in advance the length, so cannot define formatting as specified in those answers by dividing the string in chuncks.

I wrote a Java application that prints on console posts downloaded from web forums. The problem I'm facing is that since post content is saved in a string, when I print it on screen with

System.out.println(string_variable_containing_post)

it will go to new line only at the very end of the string.

This is very uncomfortable.

I would like to know if there is a way of specifying a maximum number of bytes after which insert a new line automatically.

Thanks in advance,

Matteo

if length of String abc is 200 and I want 100 characters on one line, then one dirty approach might be

System.out.println(abc.substring(0,100) + "\n" + abc.substring(100,200));

You can do this in a loop to append \\n in originial abc

You can use Guava's Splitter

 Iterable<String> lines = Splitter.fixedLength(desiredLineLength).split(string_variable_containing_post);
 for (String line : lines) {
      System.out.println(line);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM