Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a text file and storing in a String [duplicate]

Tags:

How can we read data from a text file and store in a String variable?

is it possible to pass the filename in a method and it would return the String which is the text from the file.

What kind of utilities do I have to import? A list of statements will be great.

like image 599
Mfali11 Avatar asked Apr 16 '13 01:04

Mfali11


Video Answer


1 Answers

These are the necersary imports:

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; 

And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");

String readFile(String fileName) throws IOException {     BufferedReader br = new BufferedReader(new FileReader(fileName));     try {         StringBuilder sb = new StringBuilder();         String line = br.readLine();          while (line != null) {             sb.append(line);             sb.append("\n");             line = br.readLine();         }         return sb.toString();     } finally {         br.close();     } } 
like image 131
0x6C38 Avatar answered Oct 14 '22 11:10

0x6C38