Java readfile as string

Read File as String in Java

To read File as String in Java, you can use BufferedInputStream, FileUtils of commons.io, etc. There are many ways to solve this problem of reading file to a string.

You can read file line by line, or fixed lengths of byte array in a while loop, or as a whole string based on the requirements of your application.

In this tutorial, we will learn some of the ways to read file as a string.

1. Read File as String using BufferedInputStream

In this example, we will use BufferedInputStream as the main step to read the contents of a file to a string. Following is the sequence of steps.

  1. Create file object with the path of the text file.
  2. Create a FileInputStream with the file created in the above step.
  3. Using this FileInputStream, create a BufferedInputStream.
  4. Use BufferedInputStream.readAllBytes() to read all the bytes to a byte array.
  5. Create a String with the byte array passed as argument, so that it returns a String formed using the byte array.
  6. Close BufferedInputStream and FileInputStream to release any system resources associated with the streams.
Читайте также:  Python update version ubuntu

ReadFileAsString.java

import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * Java Example Program to Read File as Sting using BufferedInputStream */ public class ReadFileAsString < public static void main(String[] args) < File file = new File("files/data.txt"); try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis)) < //read all bytes from buffered input stream and create string out of it String fileContents = new String(bis.readAllBytes()); System.out.print(fileContents); bis.close(); fis.close(); >catch (IOException e) < e.printStackTrace(); >> >

FileInputStream and BufferedInputStream could throw IOException. Hence we used Java Try with Resource.

Run the program from command prompt or in your favorite IDE.

Hello reader! Welcome to www.tutorialkart.com. Hi reader! Welcome to Java Tutorials.

2. Read File as String using commons.io

In this example, we shall use apache’s commons.io package to read file as a string.

  1. Create file object with the path to the text file.
  2. Call the method FileUtils.readFileToString() and pass the file object as argument to it. The function returns data in file as String.

ReadFileAsString.java

import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; /** * Java Example Program to Read File as Sting using commons.io */ public class ReadFileAsString < public static void main(String[] args) < File file = new File("files/data.txt"); String fileContents = ""; try < //read file as string fileContents = FileUtils.readFileToString(file); >catch (IOException e) < e.printStackTrace(); >//print contents of file System.out.print(fileContents); > >

Run the program and you get the following output.

Hello reader! Welcome to www.tutorialkart.com. Hi reader! Welcome to Java Tutorials.

Conclusion

In this Java Tutorial, we learned how to read File as String, using inbuilt classes and some external Java packages.

Источник

Java read file to String

Java read file to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometimes while working with files, we need to read the file to String in Java. Today we will look into various ways to read the file to String in Java.

Java read file to String

  1. Java read file to String using BufferedReader
  2. Read file to String in java using FileInputStream
  3. Java read file to string using Files class
  4. Read file to String using Scanner class
  5. Java read file to string using Apache Commons IO FileUtils class

java read file to string

Now let’s look into these classes and read a file to String.

Java read file to String using BufferedReader

We can use BufferedReader readLine method to read a file line by line. All we have to do is append these to a StringBuilder object with newline character. Below is the code snippet to read the file to String 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.append(line); stringBuilder.append(ls); >// delete the last new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close(); String content = stringBuilder.toString(); 

There is another efficient way 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.close(); String content = stringBuilder.toString(); 

Read file to String in java using FileInputStream

We can use FileInputStream and byte array to read file to String. You should use this method to read non-char based files such as image, 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[10]; >fis.close(); String content = sb.toString(); 

Java read file to string using Files class

We can use Files utility class to read all the file content to string in a single line of code.

String content = new String(Files.readAllBytes(Paths.get(fileName))); 

Read file to String using Scanner class

The scanner class is a quick way to read a text file to string in java.

Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); String content = scanner.useDelimiter("\\A").next(); scanner.close(); 

Java read file to string using Apache Commons IO FileUtils class

If you are using Apache Commons IO in your project, then this is a simple and quick way to read the file to string in java.

String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); 

Java read file to String example

Here is the final program with proper exception handling and showing all the different ways to read a file to string.

package com.journaldev.files; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.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 ways to read complete file contents to String * * @param args * @throws IOException */ public static void main(String[] args) < String fileName = "/Users/pankaj/Downloads/myfile.txt"; String contents = readUsingScanner(fileName); System.out.println("*****Read File to String Using Scanner*****\n" + contents); contents = readUsingApacheCommonsIO(fileName); System.out.println("*****Read File to String Using Apache Commons IO FileUtils*****\n" + contents); contents = readUsingFiles(fileName); System.out.println("*****Read File to String Using Files Class*****\n" + contents); contents = readUsingBufferedReader(fileName); System.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*****\n" + contents); contents = readUsingFileInputStream(fileName); System.out.println("*****Read File to String Using FileInputStream*****\n" + contents); >private static String readUsingBufferedReaderCharArray(String fileName) < BufferedReader reader = null; StringBuilder stringBuilder = new StringBuilder(); char[] buffer = new char[10]; try < reader = new BufferedReader(new FileReader(fileName)); while (reader.read(buffer) != -1) < stringBuilder.append(new String(buffer)); buffer = new char[10]; >> catch (IOException e) < e.printStackTrace(); >finally < if (reader != null) try < reader.close(); >catch (IOException e) < e.printStackTrace(); >> return stringBuilder.toString(); > private static String readUsingFileInputStream(String fileName) < FileInputStream fis = null; byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); try < fis = new FileInputStream(fileName); while (fis.read(buffer) != -1) < sb.append(new String(buffer)); buffer = new byte[10]; >fis.close(); > catch (IOException e) < e.printStackTrace(); >finally < if (fis != null) 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; String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) < stringBuilder.append(line); stringBuilder.append(ls); >// delete the last ls stringBuilder.deleteCharAt(stringBuilder.length() - 1); > catch (IOException e) < e.printStackTrace(); >finally < if (reader != null) try < reader.close(); >catch (IOException e) < e.printStackTrace(); >> return stringBuilder.toString(); > private static String readUsingFiles(String fileName) < try < return new String(Files.readAllBytes(Paths.get(fileName))); >catch (IOException e) < e.printStackTrace(); return null; >> private static String readUsingApacheCommonsIO(String fileName) < try < return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); >catch (IOException e) < e.printStackTrace(); return null; >> private static String readUsingScanner(String fileName) < Scanner scanner = null; try < scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); // we can use Delimiter regex as "\\A", "\\Z" or "\\z" String data = scanner.useDelimiter("\\A").next(); return data; >catch (IOException e) < e.printStackTrace(); return null; >finally < if (scanner != null) scanner.close(); >> > 

You can use any of the above ways to read file content to string in java. However, it’s not advisable if the file size is huge because you might face out of memory errors.

You can checkout more Java IO examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Read a File to String in Java

Learn to read a text file into String in Java. Following examples use Files.readAllBytes() , Files.lines() (to read line by line) and FileReader and BufferedReader to read a file to String.

1. Using Files.readString() – Java 11

With the new method readString() introduced in Java 11, it takes only a single line to read a file’s content into String using the UTF-8 charset .

  • In case of any error during the read operation, this method ensures that the file is properly closed.
  • It throws OutOfMemoryError if the file is extremely large, for example, larger than 2GB .
Path filePath = Path.of("c:/temp/demo.txt"); String content = Files.readString(fileName);

2. Using Files.lines() – Java 8

The lines() method reads all lines from a file into a Stream. The Stream is populated lazily when the stream is consumed.

  • Bytes from the file are decoded into characters using the specified charset.
  • The returned stream contains a reference to an open file. The file is closed by closing the stream.
  • The file contents should not be modified during the reading process, or else the result is undefined.
Path filePath = Path.of("c:/temp/demo.txt"); StringBuilder contentBuilder = new StringBuilder(); try (Stream stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) < stream.forEach(s ->contentBuilder.append(s).append("\n")); > catch (IOException e) < //handle exception >String fileContent = contentBuilder.toString();

3. Using Files.readAllBytes() – Java 7

The readAllBytes() method reads all the bytes from a file into a byte[]. Do not use this method for reading large files.

This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all the bytes, we pass those bytes to String class constructor to create a new String.

Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; try < byte[] bytes = Files.readAllBytes(Paths.get(filePath)); fileContent = new String (bytes); >catch (IOException e) < //handle exception >

4. Using BufferedReader – Java 6

If you are still not using Java 7 or later, then use BufferedReader class. Its readLine() method reads the file one line at a time and returns the content .

Path filePath = Path.of("c:/temp/demo.txt"); String fileContent = ""; StringBuilder contentBuilder = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) < String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) < contentBuilder.append(sCurrentLine).append("\n"); >> catch (IOException e) < e.printStackTrace(); >fileContent = contentBuilder.toString();

We can use the utility classes provided by the Apache Commons IO library. The FileUtils.readFileToString() is an excellent way to read a whole file into a String in a single statement.

File file = new File("c:/temp/demo.txt"); String content = FileUtils.readFileToString(file, "UTF-8");

Guava also provides Files class that can be used to read the file content in a single statement.

File file = new File("c:/temp/demo.txt"); String content = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8).read();

Use any of the above-given methods for reading a file into a string using Java.

Источник

Оцените статью