This question already has an answer here:
-
How do I create a Java string from the contents of a file?
34 answers
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.
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();
}
}
How can we read data from a text file and store in a String Variable?
Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.
Is it possible to pass the filename in a method and it would return the String which is the text from the file.
Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.