Overview
In this tutorial, we show you how to read file to string with utf-8 and split string by multiple spaces or split string by new line.Read file to string with utf-8
There are several ways to read a plain text file in Java, such as BufferedReader, java.nio.file.Files.lines() ... In this example, we can use java.nio.file.Files.readAllBytes() method to read file content into string. The text file is stored at C:/data/fruits.txt with following contents.Cherry Banana Chico fruit Jackfruit Kiwifruit Orange Pineapple Mango AppleThis code will read a text file into a String using java 7. Files.readAllBytes().
String filePath = "c:/data/fruits.txt"; String contents = null; try { contents = new String(Files.readAllBytes(Paths.get(filePath))); } catch (IOException e) { e.printStackTrace(); } System.out.println("##### Before split"); System.out.println(contents);
Split string by new line
New line character is different in various operating systems. In Unix, New Mac Environment, lines are just separated by the character "\n". In Windows Environment lines are just separated by the character "\r\n". The best way to split a string by new line character using Java regex \r?\n .System.out.println("##### split string by new line"); String[] lines = contents.split("\\r?\\n"); for (String line : lines) { System.out.println(line); }
Split string by multiple spaces
To split the string with one or more whitespaces we use the "\s+" regular expression. Let’s see the code snippet below.System.out.println("##### Split string by multiple spaces"); String[] fruits = contents.split("\\s+"); for(String fruit : fruits) { System.out.println(fruit); }
Full source code Split String
See the below completed source code for Split String in Java.package com.jackrutorial; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class SplitStringExample { public static void main(String[] args) { String filePath = "c:/data/fruits.txt"; String contents = null; try { contents = new String(Files.readAllBytes(Paths.get(filePath))); } catch (IOException e) { e.printStackTrace(); } System.out.println("##### Before split"); System.out.println(contents); System.out.println("##### split string by new line"); String[] lines = contents.split("\\r?\\n"); for (String line : lines) { System.out.println(line); } System.out.println("##### Split string by multiple spaces"); String[] fruits = contents.split("\\s+"); for(String fruit : fruits) { System.out.println(fruit); } } }
Console Output
##### Before split Cherry Banana Chico fruit Jackfruit Kiwifruit Orange Pineapple Mango Apple ##### split string by new line Cherry Banana Chico fruit Jackfruit Kiwifruit Orange Pineapple Mango Apple ##### Split string by multiple spaces Cherry Banana Chico fruit Jackfruit Kiwifruit Orange Pineapple Mango Apple