将输入流转换为文件 Android

4

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

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. 暂时保存并使用意图在PDF视图器中显示 注:返回的文件将为PDF格式


你最终确定了正确的解决方案吗? - IgorGanapolsky
2个回答

4

您没有说明您想要存储在外部还是内部存储中,我编写了这个示例来演示内部存储。

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并关闭需要关闭的内容。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接