Read Text File and Store in Object Java

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

Java read file to Cord

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

  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 Cord using Scanner grade
  5. Java read file to string using Apache Commons IO FileUtils form

java read file to string

Now let'southward wait into these classes and read a file to Cord.

Coffee read file to String using BufferedReader

We can utilize BufferedReader readLine method to read a file line by line. All we have to practice 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 = naught; String ls = Arrangement.getProperty("line.separator"); while ((line = reader.readLine()) != goose egg) { 	stringBuilder.suspend(line); 	stringBuilder.append(ls); } // delete the last new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close();  String content = stringBuilder.toString();                              

In that location is another efficient way to read file to Cord 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) != -ane) { 	stringBuilder.append(new Cord(buffer)); 	buffer = new char[x]; } reader.close();  String content = stringBuilder.toString();                              

Read file to String in java using FileInputStream

We can employ FileInputStream and byte array to read file to String. Y'all should utilize this method to read non-char based files such as image, video etc.

                                  FileInputStream fis = new FileInputStream(fileName); byte[] buffer = new byte[ten]; StringBuilder sb = new StringBuilder(); while (fis.read(buffer) != -1) { 	sb.append(new String(buffer)); 	buffer = new byte[x]; } fis.close();  String content = sb.toString();                              

Java read file to string using Files grade

Nosotros can apply Files utility class to read all the file content to string in a unmarried 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.shut();                              

Java read file to string using Apache Eatables IO FileUtils course

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

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

Coffee read file to String example

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

                                  bundle com.journaldev.files;  import coffee.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 coffee.nio.file.Paths; import java.util.Scanner;  import org.apache.commons.io.FileUtils;  public class JavaReadFileToString {  	/** 	 * This class shows unlike means to read consummate file contents to String 	 *  	 * @param args 	 * @throws IOException 	 */ 	public static void main(String[] args) { 		String fileName = "/Users/pankaj/Downloads/myfile.txt";  		Cord contents = readUsingScanner(fileName); 		System.out.println("*****Read File to String Using Scanner*****\northward" + contents);  		contents = readUsingApacheCommonsIO(fileName); 		Arrangement.out.println("*****Read File to Cord Using Apache Commons IO FileUtils*****\n" + contents);  		contents = readUsingFiles(fileName); 		Arrangement.out.println("*****Read File to String Using Files Course*****\n" + contents);  		contents = readUsingBufferedReader(fileName); 		Organisation.out.println("*****Read File to String Using BufferedReader*****\n" + contents);  		contents = readUsingBufferedReaderCharArray(fileName); 		System.out.println("*****Read File to String Using BufferedReader and char assortment*****\n" + contents);  		contents = readUsingFileInputStream(fileName); 		Organisation.out.println("*****Read File to String Using FileInputStream*****\north" + contents);  	}  	individual static String readUsingBufferedReaderCharArray(String fileName) { 		BufferedReader reader = naught; 		StringBuilder stringBuilder = new StringBuilder(); 		char[] buffer = new char[x]; 		try { 			reader = new BufferedReader(new FileReader(fileName)); 			while (reader.read(buffer) != -1) { 				stringBuilder.append(new Cord(buffer)); 				buffer = new char[10]; 			} 		} take hold of (IOException due east) { 			e.printStackTrace(); 		} finally { 			if (reader != null) 				endeavor { 					reader.shut(); 				} catch (IOException due east) { 					east.printStackTrace(); 				} 		}  		return stringBuilder.toString(); 	}  	individual static String readUsingFileInputStream(String fileName) { 		FileInputStream fis = nil; 		byte[] buffer = new byte[10]; 		StringBuilder sb = new StringBuilder(); 		endeavour { 			fis = new FileInputStream(fileName);  			while (fis.read(buffer) != -ane) { 				sb.append(new Cord(buffer)); 				buffer = new byte[x]; 			} 			fis.close();  		} catch (IOException due east) { 			e.printStackTrace(); 		} finally { 			if (fis != null) 				try { 					fis.close(); 				} catch (IOException e) { 					e.printStackTrace(); 				} 		} 		render sb.toString(); 	}  	private static String readUsingBufferedReader(Cord fileName) { 		BufferedReader reader = null; 		StringBuilder stringBuilder = new StringBuilder();  		endeavor { 			reader = new BufferedReader(new FileReader(fileName)); 			String line = zero; 			String ls = System.getProperty("line.separator"); 			while ((line = reader.readLine()) != cypher) { 				stringBuilder.append(line); 				stringBuilder.append(ls); 			} 			// delete the final ls 			stringBuilder.deleteCharAt(stringBuilder.length() - one); 		} catch (IOException due east) { 			e.printStackTrace(); 		} finally { 			if (reader != null) 				endeavour { 					reader.shut(); 				} grab (IOException east) { 					east.printStackTrace(); 				} 		}  		return stringBuilder.toString(); 	}  	individual static String readUsingFiles(Cord fileName) { 		effort { 			return new String(Files.readAllBytes(Paths.get(fileName))); 		} catch (IOException e) { 			e.printStackTrace(); 			return zero; 		} 	}  	individual static String readUsingApacheCommonsIO(Cord fileName) { 		try { 			return FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8); 		} catch (IOException e) { 			e.printStackTrace(); 			render null; 		} 	}  	private static Cord readUsingScanner(String fileName) { 		Scanner scanner = null; 		try { 			scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.proper noun()); 			// we can use Delimiter regex every bit "\\A", "\\Z" or "\\z" 			String data = scanner.useDelimiter("\\A").next(); 			return data; 		} catch (IOException e) { 			e.printStackTrace(); 			return aught; 		} finally { 			if (scanner != null) 				scanner.close(); 		}  	}  }                              

You can use whatever of the above ways to read file content to cord in coffee. However, it'due south non appropriate if the file size is huge because you might face out of retentivity errors.

References:

  • BufferedReader API Doc
  • Files API Doc

bernardreptereard1941.blogspot.com

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

0 Response to "Read Text File and Store in Object Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel