24

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.

Jonik
  • 80,077
  • 70
  • 264
  • 372
Mfali11
  • 353
  • 2
  • 3
  • 8
  • Java, simple java language. – Mfali11 Apr 16 '13 at 01:21
  • why you dont tag it? so let people see – Mustafa Ekici Apr 16 '13 at 01:23
  • You will need `java.io.*` – PM 77-1 Apr 16 '13 at 01:27
  • 4
    The answer to the questions "yes". Take a look at [Basic I/O](http://docs.oracle.com/javase/tutorial/essential/io/) for more details – MadProgrammer Apr 16 '13 at 01:28
  • Please share what you've tried. – jahroy Apr 16 '13 at 01:30
  • 8
    @MrD - Correction: he's asked people to do his work for him and I asked him what code he has tried. The answer is "_he hasn't tried anything_" (including google). Feel free to answer this question if you want, but I wouldn't bother. This question will just litter the site. Your answer will just encourage the OP to continue to be lazy and abuse StackOverflow. – jahroy Apr 16 '13 at 01:34

2 Answers2

75

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();
    }
}
0x6C38
  • 6,796
  • 4
  • 35
  • 47
  • 8
    You could also use Apache's FileUtils library to do this in one line... There are **SO** many questions about this it's not even funny. – jahroy Apr 16 '13 at 01:38
  • 2
    This code has several issues: How do you know the file is the platform default encoding? How do you know that encoding uses a single byte per character? Won't the FileReader need to be closed if reading throws an exception? – meriton Apr 16 '13 at 01:43
  • Here's [a better question/answer](http://stackoverflow.com/q/326390/778118) that has been around for awhile. – jahroy Apr 16 '13 at 01:59
  • There are more issues. How do you know the file size fits in an `int?` How do you know the file fits into memory? And finally, and the biggest issue of all, how do you know that `reader.read(chars)` filled the buffer? – user207421 Apr 17 '13 at 09:16
  • You can also add 'how do you know that the line separator was \n?' – user207421 Apr 17 '13 at 22:19
  • 1
    needed to insert this as the while statement to prevent null --> while ((line = br.readLine()) != null) – xhallix Apr 22 '14 at 05:17
  • @ChristophHa Adding a line terminator *after* calling `readLine()` doesn't have anything to do with what happened inside `readLine()`. – user207421 Nov 29 '15 at 20:21
-5

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    @downvoter OK, which is it? It doesn't add latency? doesn't waste memory? doesn't assume the entire file fits into memory? – user207421 Jul 28 '17 at 01:36
  • That would be great if u add some example, it would really help for beginner – Varun Jan 09 '19 at 10:57