How to Read From a File Into a String in Android

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

Java read file to Cord

There are many ways to read a file to Cord in Java. Nosotros will explore the following ways in this tutorial.

  1. Coffee read file to Cord using BufferedReader
  2. Read file to String in java using FileInputStream
  3. Java read file to string using Files grade
  4. Read file to String using Scanner course
  5. Java read file to string using Apache Eatables IO FileUtils course

java read file to string

Now allow'south wait into these classes and read a file to String.

Java read file to String using BufferedReader

Nosotros can use BufferedReader readLine method to read a file line by line. All we accept to do is append these to a StringBuilder object with newline character. Below is the lawmaking 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 = Organisation.getProperty("line.separator"); while ((line = reader.readLine()) != null) { 	stringBuilder.append(line); 	stringBuilder.append(ls); } // delete the terminal new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.shut();  String content = stringBuilder.toString();                              

There is some other efficient way to read file to Cord using BufferedReader and char assortment.

                                  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

Nosotros can use FileInputStream and byte array to read file to String. You should utilise this method to read not-char based files such as image, video etc.

                                  FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[x]; 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 cord using Files class

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

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

Read file to Cord using Scanner class

The scanner course is a quick style 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").side by side(); scanner.shut();                              

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 coffee.

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

Java read file to String example

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

                                  package com.journaldev.files;  import java.io.BufferedReader; import coffee.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.commons.io.FileUtils;  public class JavaReadFileToString {  	/** 	 * This class shows different ways to read consummate file contents to String 	 *  	 * @param args 	 * @throws IOException 	 */ 	public static void primary(Cord[] args) { 		Cord fileName = "/Users/pankaj/Downloads/myfile.txt";  		String contents = readUsingScanner(fileName); 		System.out.println("*****Read File to String Using Scanner*****\northward" + 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*****\northward" + contents);  		contents = readUsingBufferedReaderCharArray(fileName); 		System.out.println("*****Read File to String Using BufferedReader and char array*****\north" + contents);  		contents = readUsingFileInputStream(fileName); 		System.out.println("*****Read File to String Using FileInputStream*****\due north" + contents);  	}  	private static String readUsingBufferedReaderCharArray(String fileName) { 		BufferedReader reader = null; 		StringBuilder stringBuilder = new StringBuilder(); 		char[] buffer = new char[x]; 		try { 			reader = new BufferedReader(new FileReader(fileName)); 			while (reader.read(buffer) != -1) { 				stringBuilder.suspend(new String(buffer)); 				buffer = new char[10]; 			} 		} catch (IOException e) { 			due east.printStackTrace(); 		} finally { 			if (reader != null) 				try { 					reader.close(); 				} catch (IOException e) { 					east.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 eastward) { 			due east.printStackTrace(); 		} finally { 			if (fis != aught) 				try { 					fis.close(); 				} catch (IOException eastward) { 					e.printStackTrace(); 				} 		} 		render 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 = Arrangement.getProperty("line.separator"); 			while ((line = reader.readLine()) != null) { 				stringBuilder.append(line); 				stringBuilder.append(ls); 			} 			// delete the last ls 			stringBuilder.deleteCharAt(stringBuilder.length() - one); 		} catch (IOException east) { 			e.printStackTrace(); 		} finally { 			if (reader != null) 				attempt { 					reader.close(); 				} catch (IOException e) { 					eastward.printStackTrace(); 				} 		}  		render stringBuilder.toString(); 	}  	private static String readUsingFiles(String fileName) { 		endeavour { 			return new String(Files.readAllBytes(Paths.become(fileName))); 		} take hold of (IOException east) { 			east.printStackTrace(); 			return null; 		} 	}  	individual static String readUsingApacheCommonsIO(String fileName) { 		endeavor { 			render FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); 		} take hold of (IOException due east) { 			e.printStackTrace(); 			return null; 		} 	}  	private static Cord readUsingScanner(String fileName) { 		Scanner scanner = null; 		endeavor { 			scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name()); 			// we tin can use Delimiter regex as "\\A", "\\Z" or "\\z" 			Cord data = scanner.useDelimiter("\\A").next(); 			return data; 		} catch (IOException e) { 			e.printStackTrace(); 			render null; 		} finally { 			if (scanner != aught) 				scanner.shut(); 		}  	}  }                              

You can utilize any of the in a higher place ways to read file content to cord in java. Withal, information technology'south not appropriate if the file size is huge because you might face out of retention errors.

References:

  • BufferedReader API Doc
  • Files API Dr.

saineponsibleaut.blogspot.com

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

0 Response to "How to Read From a File Into a String in Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel