【问题标题】:Convert input stream into file android将输入流转换为文件android
【发布时间】:2017-09-06 15:43:52
【问题描述】:

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

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查看器中显示 注意:返回的文件将是pdf格式

【问题讨论】:

  • 你有没有找到正确的解决方案?

标签: android file inputstream


【解决方案1】:

您可以使用以下代码将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();
            }
        }
    }

【讨论】:

    【解决方案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 并关闭需要关闭的内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2011-09-30
      • 2016-11-24
      相关资源
      最近更新 更多