Zeus
Zeus

Reputation: 2253

Reading an InputStream in Java

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.

Upvotes: 0

Views: 111

Answers (2)

kai
kai

Reputation: 6887

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

Upvotes: 1

Landei
Landei

Reputation: 54584

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

Upvotes: 0

Related Questions