将输入流转换为文件android

时间:2017-04-11 10:02:48

标签: android file inputstream

在我的应用程序中,我使用下面的代码返回输入流

QBContent.downloadFileById(fileId, new QBEntityCallback<InputStream>() {
@Override
public void onSuccess(final InputStream inputStream, Bundle params) {
    long length = params.getLong(Consts.CONTENT_LENGTH_TAG);
    Log.i(TAG, "content.length: " + length);

    // use inputStream to download a file
}

@Override
public void onError(QBResponseException errors) {

}
}, new QBProgressCallback() {
@Override
public void onProgressUpdate(int progress) {

}
});

现在我想将输入转换为文件,然后想用该文件做两件事  1.如何将其保存到用户的手机存储空间  2.暂时保存并使用intent在pdf viewer中显示它  注意:返回的文件将采用pdf正式

2 个答案:

答案 0 :(得分:2)

您没有提及是否要存储在外部或内部存储中,我为内部存储编写了此示例

BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
    total.append(line).append('\n');
}

try {
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("file.txt", Context.MODE_PRIVATE));
  outputStreamWriter.write(total.toString());
  outputStreamWriter.close();
}
catch (IOException e) {
    Log.e("Exception", "File write failed: " + e.toString());
}

不要忘记使用try/catch并关闭需要关闭的内容

答案 1 :(得分:0)

您可以使用以下代码在文件中存储InputStream

但是您需要传递文件路径以及要将文件存储在存储中的位置。

InputStream inputStream = null;
BufferedReader br = null;

try {
    // read this file into InputStream
    inputStream = new FileInputStream("/Users/mkyong/Downloads/file.js");
    br = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    System.out.println(sb.toString());
    System.out.println("\nDone!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }