0

I'm new to Java thus the question,

I'm using the following class to read a file into a string.

public class Reader {

    public static 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 I modify the method signature of read to read a InputStream as opposed to a string.

Zeus
  • 1,853
  • 4
  • 21
  • 42
  • I'm new to Java, down voter your argument please ? – Zeus Apr 01 '16 at 14:35
  • YOu mean just send it an `InputStream` and then just do... `BufferedInputStream st = new BufferedInputStream(*PARAMETER*);` ?? – 3kings Apr 01 '16 at 14:36
  • Are you looking for `public static String readInputStream(InputStream stream)` or `public static InputStream readFile(String filename)` ? – Shark Apr 01 '16 at 14:36
  • Possible duplicate of [Read/convert an InputStream to a String](http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string) – Landei Apr 01 '16 at 15:03

2 Answers2

1

Remove the String argument and create an argument of type InputStream. Pass this argument to the constructor of an InputStreamReader and this InputStreamReader can be passed to the constructor of your BufferedReader.

public static String readFile(InputStream is) throws IOException
{
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    .
    .
    .
}

Maybee you want to try a try-with-resource statement. Then you can remove the final block. It looks like this.

public static String readFile(InputStream is) throws IOException
{
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is)))
    {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null)
        {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    }
}
kai
  • 6,219
  • 16
  • 37
0

If it is not for educational purposes, don't do this manually. E.g. you could use IOUtils.toString from Apache Commons.

Landei
  • 52,346
  • 12
  • 89
  • 188