Possible Duplicate:
How to create a Java String from the contents of a file
I have a .txt file that I want to save in a String variable. I imported the file with File f = new File("test.txt");
. Now I am trying to put the contents of it in a String
variable. I can not find a clear explanation for how to do this.
asked Dec 13, 2012 at 1:56
-
1Welcome to the site. When you prepare your question, please pay attention to the possible duplicate box. As it turns out, this is a quite common request.Sergey Kalinichenko– Sergey Kalinichenko12/13/2012 02:00:55Commented Dec 13, 2012 at 2:00
-
Have you ever seen my answer to your other question? If not, see it here: stackoverflow.com/a/13852139/540552Victor Stafusa– Victor Stafusa12/13/2012 19:38:30Commented Dec 13, 2012 at 19:38
2 Answers 2
Use a Scanner
:
Scanner file = new Scanner(new File("test.txt"));
String contents = file.nextLine();
file.close();
Of course, if your file has multiple lines you can call nextLine
multiple times.
answered Dec 13, 2012 at 2:00
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
answered Dec 13, 2012 at 2:10
lang-java