java

How to read the contents of a file into a String in Java

In this tutorial, we are going to see how to read the contents of a file into a String in Java 6, 7 and 8.

  • By using InputStreamReader & BufferedReader (Java 6)
  • By using Files.readAllBytes() (Java 7)
  • By using Files.lines() (Java 8)

 

How to read the contents of a file into a String in Java 6:
import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
	   
		InputStream is = new FileInputStream("file.txt");
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader buffer = new BufferedReader(isr);
				
		String line = buffer.readLine();
		StringBuilder builder = new StringBuilder();
				
		while(line != null){
		   builder.append(line).append("\n");
		   line = buffer.readLine();
		}
				
		String str = builder.toString();
		System.out.println(str);
   }
}

 
[st_adsense]  
As you can see, it’s a bit difficult, you have to write a lot of unnecessary code just to read the contents of the file into a String. Now let’s look at how to read a file in a String in JDK 1.7
 

How to read the contents of a file into a String in Java 7:
import java.nio.file.*;
import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
	  String str = new String(Files.readAllBytes(Paths.get("file.txt")));
	  System.out.println(str);
   }
}

It’s almost easier using Java 7. In fact, it gets easier with Streams & lambda expression in Java 8.
 
[st_adsense]  

How to read the contents of a file into a String in Java 8:

There is a really nice new feature in Java 8 that allows you to get a stream from a file in a single line, using Streams. You can manipulate the stream with the following method filter(), map(), limit(), skip(), etc.

import java.nio.file.*;
import java.io.*;

public class Main {
   public static void main(String[] args) throws IOException {
        Files.lines(Paths.get("file.txt")).forEach(System.out::println);
   }
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More [st_adsense]

Leave a Reply

Your email address will not be published. Required fields are marked *