Java Convert File to String
By:Roy.LiuLast updated:2019-08-11
In Java, we have many ways to convert a File to a String.
A text file for testing later.
c:\\projects\\app.log
1. Java 11 – Files.readString
A new method Files.readString is added in java.nio.file.Files, it makes reading a string from File much easier.
FileToString1.java
package com.mkyong; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FileToString1 { public static void main(String[] args) { String path = "c:\\projects\\app.log"; try { // default StandardCharsets.UTF_8 String content = Files.readString(Paths.get(path)); System.out.println(content); } catch (IOException e) { e.printStackTrace();
Terminal
2. Java 8 – Files.lines
Convert a File into a Stream and join it.
FileToString2.java
package com.mkyong; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileToString2 { public static void main(String[] args) { String path = "c:\\projects\\app.log"; try (Stream<String> lines = Files.lines(Paths.get(path))) { // Formatting like \r\n will be lost // String content = lines.collect(Collectors.joining()); // UNIX \n, WIndows \r\n String content = lines.collect(Collectors.joining(System.lineSeparator())); System.out.println(content); // File to List //List<String> list = lines.collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace();
Terminal
3. Java 7 – Files.readAllLines
Convert a File into a List
FileExample3.java
package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class FileToString3 { public static void main(String[] args) { String path = "c:\\projects\\app.log"; try { // default StandardCharsets.UTF_8 // Java 8 // List<String> content = Files.readAllLines(Paths.get(path)); // Java 7 List<String> content = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8); System.out.println(content); } catch (IOException e) { e.printStackTrace();
Output
Terminal
[A, B, C, D, E]
4. Apache Commons IO
pom.xml
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
FileToString4.java
package com.mkyong; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; public class FileToString4 { public static void main(String[] args) { String path = "c:\\projects\\app.log"; try { String content = FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8); System.out.println(content); } catch (IOException e) { e.printStackTrace();
Output
Terminal
From:一号门
COMMENTS