使用android中的缓冲读取器读取大文件数据

时间:2015-04-25 14:58:24

标签: java android

嗨我想用缓冲的阅读器将大型远程文件读入字符串。但是我得到了远程文件的一半数据。

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputstream),8*1024);

        StringBuilder sb = new StringBuilder(999999);
        String line;

        while ((line = reader.readLine()) != null) {
            Log.e("Line is ",line);
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        Log.e("Content: ", sb.toString());

如何获取远程文件的完整数据?

1 个答案:

答案 0 :(得分:0)

您的代码似乎没有任何问题,但您可以以这种方式尝试:

private String ReceiveData(InputStream inputstream){

        StringBuilder sb = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( inputstream),8*1024);
        sb = new StringBuilder();
        String str;
        int numRead = 0;

        try {
            if (bufferedReader!=null) {
                if (bufferedReader.ready()) {

                    try {
                        while ((numRead = bufferedReader.read()) >= 0) {

                            //convert asci to char and then to string
                            str = String.valueOf((char) numRead);

                            if ((str != null)&& (str.toString() != "")) {

                                sb.append(str);
                            }

                            if (!bufferedReader.ready()){
                                //no more characters to read
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    //loop exited, check for null
                    if (sb != null) {
                        return sb.toString();
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

希望我帮助过。