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.

Community
  • 1
  • 1
vegetablelasagna
  • 29
  • 1
  • 2
  • 6

2 Answers2

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
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();
}
Wilts C
  • 1,720
  • 1
  • 21
  • 28