Java How to Read a Text File Into a String

Sometimes while working with files, we demand to read the file to String in Coffee. Today we volition expect into diverse ways 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. We will explore the post-obit ways in this tutorial.

  1. Coffee 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 Cord using Scanner class
  5. Coffee read file to string using Apache Commons IO FileUtils class

java read file to string

Now let's await into these classes and read a file to String.

Java read file to String using BufferedReader

We tin 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. Beneath is the code snippet to read the file to Cord using BufferedReader.

                                  BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); String line = null; Cord ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != cipher) { 	stringBuilder.append(line); 	stringBuilder.append(ls); } // delete the last new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close();  String content = stringBuilder.toString();                              

At that place is another efficient style 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[ten]; while (reader.read(buffer) != -1) { 	stringBuilder.append(new String(buffer)); 	buffer = new char[10]; } reader.close();  String content = stringBuilder.toString();                              

Read file to Cord in java using FileInputStream

We can use FileInputStream and byte array to read file to String. Yous should use this method to read non-char based files such as prototype, video etc.

                                  FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[10]; StringBuilder sb = new StringBuilder(); while (fis.read(buffer) != -1) { 	sb.append(new Cord(buffer)); 	buffer = new byte[10]; } fis.shut();  Cord content = sb.toString();                              

Java read file to string using Files form

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

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

Read file to String using Scanner class

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

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

Java read file to string using Apache Commons IO FileUtils class

If you are using Apache Eatables IO in your projection, then this is a unproblematic and quick fashion to read the file to string in java.

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

Coffee read file to Cord example

Hither is the final programme with proper exception handling and showing all the different ways to read a file to cord.

                                  packet com.journaldev.files;  import java.io.BufferedReader; import java.io.File; import coffee.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.eatables.io.FileUtils;  public class JavaReadFileToString {  	/** 	 * This class shows different ways to read complete file contents to Cord 	 *  	 * @param args 	 * @throws IOException 	 */ 	public static void main(String[] args) { 		String fileName = "/Users/pankaj/Downloads/myfile.txt";  		String contents = readUsingScanner(fileName); 		Organisation.out.println("*****Read File to String Using Scanner*****\n" + contents);  		contents = readUsingApacheCommonsIO(fileName); 		System.out.println("*****Read File to Cord 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); 		System.out.println("*****Read File to Cord 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.suspend(new String(buffer)); 				buffer = new char[10]; 			} 		} catch (IOException e) { 			e.printStackTrace(); 		} finally { 			if (reader != goose egg) 				effort { 					reader.close(); 				} catch (IOException east) { 					e.printStackTrace(); 				} 		}  		return stringBuilder.toString(); 	}  	individual static String readUsingFileInputStream(Cord fileName) { 		FileInputStream fis = null; 		byte[] buffer = new byte[10]; 		StringBuilder sb = new StringBuilder(); 		try { 			fis = new FileInputStream(fileName);  			while (fis.read(buffer) != -i) { 				sb.suspend(new String(buffer)); 				buffer = new byte[10]; 			} 			fis.shut();  		} catch (IOException eastward) { 			due east.printStackTrace(); 		} finally { 			if (fis != null) 				try { 					fis.shut(); 				} catch (IOException e) { 					eastward.printStackTrace(); 				} 		} 		return sb.toString(); 	}  	private static Cord readUsingBufferedReader(String fileName) { 		BufferedReader reader = null; 		StringBuilder stringBuilder = new StringBuilder();  		try { 			reader = new BufferedReader(new FileReader(fileName)); 			Cord line = null; 			String ls = Arrangement.getProperty("line.separator"); 			while ((line = reader.readLine()) != naught) { 				stringBuilder.suspend(line); 				stringBuilder.suspend(ls); 			} 			// delete the last ls 			stringBuilder.deleteCharAt(stringBuilder.length() - ane); 		} catch (IOException due east) { 			e.printStackTrace(); 		} finally { 			if (reader != null) 				try { 					reader.close(); 				} catch (IOException e) { 					e.printStackTrace(); 				} 		}  		render stringBuilder.toString(); 	}  	individual 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 zip; 		} 	}  	private static String readUsingScanner(String fileName) { 		Scanner scanner = nix; 		try { 			scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); 			// we can utilise Delimiter regex as "\\A", "\\Z" or "\\z" 			Cord data = scanner.useDelimiter("\\A").next(); 			return information; 		} grab (IOException e) { 			east.printStackTrace(); 			return cypher; 		} finally { 			if (scanner != null) 				scanner.close(); 		}  	}  }                              

You can utilize any of the higher up means to read file content to string in java. However, it'due south not appropriate if the file size is huge because you might face up out of memory errors.

References:

  • BufferedReader API Doctor
  • Files API Physician

roundsorwits.blogspot.com

Source: https://www.journaldev.com/875/java-read-file-to-string

0 Response to "Java How to Read a Text File Into a String"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel