There was no tardily agency to read a text file every bit String inwards Java until JDK 7, which released NIO 2. This API straightaway provides a duet of utility methods which you lot tin move to read entire file every bit String e.g. Files.readAllBytes() returns a byte array of the entire text file. You tin convert that byte array to String to convey a whole text file every bit String within your Java program. If you lot bespeak all lines of files every bit List of String e.g. into an ArrayList, you lot tin move Files.readAllLines() method. This render a List of String, where each String represents a unmarried trouble of the file. Prior to these API changes, I used to move the BufferedReader together with StringBuilder to read the entire text file every bit String. You iterate through the file, reading i trouble at a fourth dimension using readLine() method together with appending them into a StringBuilder until you lot accomplish the halt of the file. You tin nonetheless move this method if you lot are running on Java SE half dozen or lower version.
In this article, we'll await at a duet of examples to demonstrate how to read a text file every bit String, or acquire a List of lines every bit String from a text file. I'll besides demo the BufferedReader way, which you lot tin move inwards Java SE half dozen together with before version.
Here is the method to read a file every bit String inwards Java 7:
You should besides live on careful amongst grapheme encoding. Above code assumes that file together with platform's default grapheme encoding is same. If that's non the instance hence move the right grapheme encoding piece converting byte array to String inwards Java. See Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than almost grapheme encoding together with converting bytes to text inwards Java.
Don't forget to append the \n grapheme to insert the trouble break, otherwise, all lines volition live on joined together together with all text from the file volition come upwardly every bit only i big line. If you lot are non familiar amongst \n or \r\n, I advise you lot read Big Java: Early Objects fifth Edition yesteryear Cay S. Horstmann to larn to a greater extent than almost special characters inwards Java.
In the 2d example, don't forget to append the "\n" or "\r\n" depending upon whether you lot are running on Windows or UNIX, otherwise all lines of files are concatenated into only i line. Also, don't forget to closed the BufferedReader to preclude resources leak, peculiarly when you lot are non using automatic resources management characteristic of Java 7.
That's all almost how to read a text file every bit String inwards Java. You tin move the novel agency if your plan is running on JRE vii together with onetime agency if you lot are using Java half dozen or lower versions. Pay attending to grapheme encoding of the file if you lot are non certain whether both file together with platform's default grapheme encoding (the machine where your Java plan is running) is non same.
Related Java File tutorials you lot may like
References
Official JDK vii File IO tutorial
Java documentation of Files degree inwards JDK 7
In this article, we'll await at a duet of examples to demonstrate how to read a text file every bit String, or acquire a List of lines every bit String from a text file. I'll besides demo the BufferedReader way, which you lot tin move inwards Java SE half dozen together with before version.
Reading Text File every bit String inwards Java 7
This is the measure agency to read the whole file every bit String inwards Java. Just brand certain the file is a small-scale or medium size together with you lot convey plenty heap infinite to concur the text from a file into memory. If you lot don't convey plenty memory, the below code tin throw java.lang.OutOfMemoryError: Java heap space, hence beware of that.Here is the method to read a file every bit String inwards Java 7:
public static String readFileAsString(String fileName) { String text = ""; try { text = new String(Files.readAllBytes(Paths.get("file.txt"))); } catch (IOException e) { e.printStackTrace(); } return text; }
You should besides live on careful amongst grapheme encoding. Above code assumes that file together with platform's default grapheme encoding is same. If that's non the instance hence move the right grapheme encoding piece converting byte array to String inwards Java. See Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn to a greater extent than almost grapheme encoding together with converting bytes to text inwards Java.
Reading Text File every bit String inwards Java 6
This was the onetime agency to reading a file every bit String inwards Java. You tin run across that it require almost 8 to 10 lines of code, which tin straightaway effectively live on done inwards only i trouble inwards Java 7. It uses the readLine() method to read the file trouble yesteryear line together with hence joined them together using StringBuilder's append() method.BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String trouble = br.readLine(); while (line != null) { sb.append(line).append("\n"); trouble = br.readLine(); } String fileAsString = sb.toString();
Don't forget to append the \n grapheme to insert the trouble break, otherwise, all lines volition live on joined together together with all text from the file volition come upwardly every bit only i big line. If you lot are non familiar amongst \n or \r\n, I advise you lot read Big Java: Early Objects fifth Edition yesteryear Cay S. Horstmann to larn to a greater extent than almost special characters inwards Java.
Java Program to read a text file every bit String
Here is the consummate Java plan to read a text file every bit String, it includes both JDK half dozen together with JDK vii approach to reading the content of the file inwards a String variable.import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /* * Java Program read a text file every bit String * outset yesteryear using the JDK vii utility method Files.readAllBytes() * together with 2d yesteryear using BufferedReader together with StringBuilder. */ public class ReadFileAsString { public static void main(String[] args) throws Exception { // read whole file every bit String inwards JDK 7 String data = ""; try { data = new String(Files.readAllBytes(Paths.get("file.txt"))); } catch (IOException e) { e.printStackTrace(); } System.out.println("Text file every bit String inwards Java"); System.out.println(data); // read file every bit String inwards Java SE half dozen together with lower version BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String trouble = br.readLine(); while (line != null) { sb.append(line).append("\n"); trouble = br.readLine(); } String fileAsString = sb.toString(); System.out .println("whole file every bit String using BufferedReader together with StringBuilder"); System.out.println(fileAsString); br.close(); } } Output Text file every bit String in Java Effective Java is the best majority for senior Developers. Clean code is the best majority for Junior Developers. whole file every bit String using BufferedReader and StringBuilder Effective Java is the best majority for senior Developers. Clean code is the best majority for Junior Developers.
In the 2d example, don't forget to append the "\n" or "\r\n" depending upon whether you lot are running on Windows or UNIX, otherwise all lines of files are concatenated into only i line. Also, don't forget to closed the BufferedReader to preclude resources leak, peculiarly when you lot are non using automatic resources management characteristic of Java 7.
That's all almost how to read a text file every bit String inwards Java. You tin move the novel agency if your plan is running on JRE vii together with onetime agency if you lot are using Java half dozen or lower versions. Pay attending to grapheme encoding of the file if you lot are non certain whether both file together with platform's default grapheme encoding (the machine where your Java plan is running) is non same.
Related Java File tutorials you lot may like
- How to write to a file using BufferedWriter inwards Java? (solution)
- How to read/write an XLSX file inwards Java? (solution)
- How to read a text file using BufferedReader inwards Java? (example)
- How to charge information from a CSV file inwards Java? (example)
- How to append text to a file inwards Java? (solution)
- How to read InputStream every bit Stream inwards Java? (example)
- How to uncovering the highest occurring give-and-take from a file inwards Java? (solution)
- 2 ways to read a text file inwards Java? (solution)
References
Official JDK vii File IO tutorial
Java documentation of Files degree inwards JDK 7

0 Response to "How to read a text file equally String inward Java"
Posting Komentar