'Large Paragraph where in each line if it exceeds certain length , should go to new line using Java

Need help on solving below usecase using Java where in the below paragraph

input

A@123@456789@10111213
B@123@456789
C@123@456789@101112131415
D@123@456789
E@123@456789@101112131415161718

has to be changed to this way below

output

A@123@4567
89@1011121
3
B@123@4567
89
C@123@4567
89@1011121
31415
D@123@4567
89
E@123@4567
89@1011121
3141516171
8

meaning each line in the given paragraph is checked for a certain length in this case 10 , and if it exceeds a newline has to be added. This behavior has to be applied on every line in the paragraph

Any help ?



Solution 1:[1]

You can achieve it like this

public static void main(String[] args) throws IOException {
            
            List<String> lines = Files.readAllLines(Paths.get("C:\\Path\\to\\File\\Test.txt"), StandardCharsets.US_ASCII);
            for(String s : lines) {
                int count=s.length()/10;
                if(s.length()%10!=0) {
                    count=(s.length()/10)+1; 
                }
                for(int i=0;i<count;i++) {
                    if(((i+1)*10)>s.length()) {
                        System.out.println(s.substring(i*10,s.length()));
                    }else
                    System.out.println(s.substring(i*10,(i+1)*10));
                }
            }
        
        }

By this way, you can split the file contents into your desired length.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Umeshwaran