0

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.

2
  • 1
    Welcome 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. Commented 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/540552 Commented Dec 13, 2012 at 19:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.