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.

4
  • I'm new to Java, down voter your argument please ? Commented Apr 1, 2016 at 14:35
  • YOu mean just send it an InputStream and then just do... BufferedInputStream st = new BufferedInputStream(*PARAMETER*); ?? Commented Apr 1, 2016 at 14:36
  • Are you looking for public static String readInputStream(InputStream stream) or public static InputStream readFile(String filename) ? Commented Apr 1, 2016 at 14:36
  • Possible duplicate of Read/convert an InputStream to a String Commented Apr 1, 2016 at 15:03

2 Answers 2

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had no idea this was so simple. Thanks.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.