How to Split String by New Line in Java Program

Spliting String by New Line in Java

In this post, we will show you simple example program about, How to split string by new line in Java. The example program has been tested and shared in the same post.

Example Program

package com.dineshkrish;

import java.util.Arrays;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class Example {

	public static String[] split(String str) {

		String[] lines = null;

		final String regx = "\\r?\\n";

		if (str != null) {
			lines = str.split(regx);
		}

		return lines;
	}

	public static void main(String[] args) {

		StringBuffer sb = new StringBuffer();

		sb.append("Line1\n");
		sb.append("Line2\n");
		sb.append("Line3\n");
		sb.append("Line4\n");
		sb.append("Line5\n");
		sb.append("Line6\n");
		sb.append("Line7\n");
		sb.append("Line8\n");
		sb.append("Line9\n");
		sb.append("Line10\n");

		System.out.println("Brefore Split\n.......................");
		
		System.out.println(sb.toString());
		
		String[] lines = split(sb.toString());

		System.out.println("After Split\n.......................");
		
		System.out.println(Arrays.deepToString(lines));
	}
}

Output

Brefore Split
.......................
Line1
Line2
Line3
Line4
Line5
Line6
Line7
Line8
Line9
Line10

After Split
.......................
[Line1, Line2, Line3, Line4, Line5, Line6, Line7, Line8, Line9, Line10]

Refrences

1. JavaDoc – String.split() method
2. JavaDoc – StringBuffer Class