Question

I had a method like this in an Android app reading a raw file:

public String inputStreamToString(InputStream isTwo) throws IOException {
        StringBuffer sBuffer = new StringBuffer();
        DataInputStream dataIO = new DataInputStream(isTwo);
        String strLineTwo = null;
        while ((strLineTwo = dataIO.readLine()) != null) {
            sBuffer.append(strLineTwo + "\n");
        }
        dataIO.close();
        isTwo.close();
        return sBuffer.toString();

    }

However, the DataInputStream object appears to be deprecated now. I researched it and heard it is better to wrap the readline() with a BufferedInputStream. Can someone help me finish his (fill in the missing line)? I am not sure how to declare the br var. This is what I have so far:

public String inputStreamToString(InputStream isTwo) throws IOException {
        String strLineTwo = null;
        BufferedReader br = null;

        StringBuffer sBuffer = new StringBuffer();
        InputStreamReader dataIO = new InputStreamReader(isTwo);


        while ((strLineTwo = br.readLine()) != null) {
            sBuffer.append(strLineTwo + "\n");
        }

        dataIO.close();
        isTwo.close();
        return sBuffer.toString();

Here is the preceding code I have not touched yet that calls this method:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tech);
        InputStream iFileTwo = getResources().openRawResource(R.raw.testing);
        try {
            TextView helpText = (TextView) findViewById(R.id.tvStream);
            String strFileTwo = inputStreamToString(iFileTwo);
            helpText.setText(strFileTwo);

        } catch (Exception e) {
            Log.e(DEBUG_TAG_THREE, "InputStreamToString failure", e);
        }
    }

Also, I want to make sure it works from Android 2.3 to 4.2 (current). Thanks for any help.

Was it helpful?

Solution

This is how I would write it. This has much less overhead and preserves the newlines as they were originally.

public String inputStreamToString(InputStream in) throws IOException {
    StringBuilder out = new StringBuilder();
    char[] chars = new char[1024];
    Reader reader = new InputStreamReader(in /*, CHARSET_TO_USE */);

    try {
        for (int len; (len = reader.read(chars)) > 0; )
            out.append(chars, 0, len);
    } finally {
        try {
            in.close();
        } catch (IOException ignored) {
        }
    }
    return out.toString();
}

OTHER TIPS

Just a suggestion, if you are migrating, then why not use the IOUtils from libraries like apache commons etc which actually take care of managing your streams and also save you with lot of errorneous conditions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top