1

我在读取原始文件的 Android 应用程序中有这样的方法:

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

    }

但是,DataInputStream 对象现在似乎已被弃用。我研究了它,听说最好readline()BufferedInputStream. 有人可以帮我完成他的(填写缺失的行)吗?我不确定如何声明brvar。这是我到目前为止所拥有的:

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

这是调用此方法的前面我尚未触及的代码:

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

另外,我想确保它适用于 Android 2.3 到 4.2(当前)。谢谢你的帮助。

4

2 回答 2

4

我就是这样写的。这具有更少的开销并保留了原来的换行符。

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();
}
于 2012-12-19T16:41:15.797 回答
0

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

于 2012-12-19T17:30:34.660 回答