Java Read Contents of File Into String
Sometimes while working with files, nosotros need to read the file to String in Java. Today we volition wait into various means to read the file to String in Java.
Coffee read file to String
There are many ways to read a file to String in Java. Nosotros will explore the following ways in this tutorial.
- Java read file to String using BufferedReader
- Read file to String in java using FileInputStream
- Java read file to string using Files class
- Read file to String using Scanner class
- Java read file to string using Apache Eatables IO FileUtils form
Now allow'south await into these classes and read a file to String.
Java read file to String using BufferedReader
We can employ BufferedReader readLine method to read a file line by line. All we have to do is suspend these to a StringBuilder object with newline character. Below is the lawmaking snippet to read the file to Cord using BufferedReader.
BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); String line = null; String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { stringBuilder.suspend(line); stringBuilder.append(ls); } // delete the last new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close(); String content = stringBuilder.toString(); In that location is another efficient fashion to read file to String using BufferedReader and char array.
BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; while (reader.read(buffer) != -1) { stringBuilder.append(new String(buffer)); buffer = new char[10]; } reader.shut(); String content = stringBuilder.toString(); Read file to String in java using FileInputStream
Nosotros tin employ FileInputStream and byte array to read file to Cord. You should use this method to read not-char based files such every bit epitome, video etc.
FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); while (fis.read(buffer) != -1) { sb.append(new String(buffer)); buffer = new byte[ten]; } fis.close(); String content = sb.toString(); Java read file to cord using Files class
We tin use Files utility grade to read all the file content to cord in a single line of code.
Cord content = new Cord(Files.readAllBytes(Paths.get(fileName))); Read file to String using Scanner course
The scanner class is a quick way to read a text file to string in coffee.
Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.proper noun()); String content = scanner.useDelimiter("\\A").adjacent(); scanner.close(); Java read file to string using Apache Commons IO FileUtils grade
If you are using Apache Commons IO in your project, then this is a simple and quick manner to read the file to cord in java.
Cord content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); Java read file to String case
Here is the final program with proper exception handling and showing all the unlike means to read a file to string.
package com.journaldev.files; import java.io.BufferedReader; import java.io.File; import coffee.io.FileInputStream; import coffee.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import org.apache.commons.io.FileUtils; public class JavaReadFileToString { /** * This class shows different means to read consummate file contents to Cord * * @param args * @throws IOException */ public static void primary(String[] args) { String fileName = "/Users/pankaj/Downloads/myfile.txt"; String contents = readUsingScanner(fileName); Arrangement.out.println("*****Read File to Cord Using Scanner*****\n" + contents); contents = readUsingApacheCommonsIO(fileName); Arrangement.out.println("*****Read File to String Using Apache Commons IO FileUtils*****\n" + contents); contents = readUsingFiles(fileName); Organisation.out.println("*****Read File to Cord Using Files Class*****\n" + contents); contents = readUsingBufferedReader(fileName); Organisation.out.println("*****Read File to String Using BufferedReader*****\n" + contents); contents = readUsingBufferedReaderCharArray(fileName); System.out.println("*****Read File to String Using BufferedReader and char array*****\north" + contents); contents = readUsingFileInputStream(fileName); Organization.out.println("*****Read File to Cord Using FileInputStream*****\north" + contents); } private static String readUsingBufferedReaderCharArray(String fileName) { BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; endeavor { reader = new BufferedReader(new FileReader(fileName)); while (reader.read(buffer) != -ane) { stringBuilder.append(new String(buffer)); buffer = new char[ten]; } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != cypher) try { reader.shut(); } take hold of (IOException e) { due east.printStackTrace(); } } return stringBuilder.toString(); } private static Cord readUsingFileInputStream(String fileName) { FileInputStream fis = null; byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); try { fis = new FileInputStream(fileName); while (fis.read(buffer) != -ane) { sb.append(new Cord(buffer)); buffer = new byte[10]; } fis.shut(); } catch (IOException e) { east.printStackTrace(); } finally { if (fis != zero) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } private static String readUsingBufferedReader(String fileName) { BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); try { reader = new BufferedReader(new FileReader(fileName)); String line = null; Cord ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != cipher) { stringBuilder.append(line); stringBuilder.append(ls); } // delete the final ls stringBuilder.deleteCharAt(stringBuilder.length() - 1); } catch (IOException due east) { e.printStackTrace(); } finally { if (reader != nada) endeavor { reader.close(); } take hold of (IOException e) { due east.printStackTrace(); } } return stringBuilder.toString(); } private static String readUsingFiles(String fileName) { try { return new Cord(Files.readAllBytes(Paths.get(fileName))); } catch (IOException e) { e.printStackTrace(); return naught; } } private static String readUsingApacheCommonsIO(String fileName) { endeavour { render FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); } catch (IOException due east) { e.printStackTrace(); render zip; } } individual static String readUsingScanner(String fileName) { Scanner scanner = nada; attempt { scanner = new Scanner(Paths.go(fileName), StandardCharsets.UTF_8.proper name()); // nosotros can use Delimiter regex as "\\A", "\\Z" or "\\z" String data = scanner.useDelimiter("\\A").next(); return data; } catch (IOException due east) { east.printStackTrace(); render nothing; } finally { if (scanner != null) scanner.shut(); } } } You lot can use any of the above ways to read file content to string in coffee. Notwithstanding, information technology'due south not advisable if the file size is huge because you might face up out of retention errors.
References:
- BufferedReader API Doc
- Files API Md
Source: https://www.journaldev.com/875/java-read-file-to-string
0 Response to "Java Read Contents of File Into String"
Post a Comment