写一段android 把接口返回的文件流保存到本地最近文件夹中
时间: 2024-02-22 11:54:52 浏览: 81
Android 实现将Bitmap 保存到本地
好的,以下是一个简单的实现方式:
```java
public class SaveFileTask extends AsyncTask<String, Void, Boolean> {
private Context mContext;
private String mFileName;
private InputStream mInputStream;
public SaveFileTask(Context context, String fileName, InputStream inputStream) {
mContext = context;
mFileName = fileName;
mInputStream = inputStream;
}
@Override
protected Boolean doInBackground(String... params) {
boolean result = false;
try {
File dir = mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
if (dir != null && !dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, mFileName);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = mInputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (mInputStream != null) {
try {
mInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(mContext, "文件已保存到最近文件夹中", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "保存文件失败", Toast.LENGTH_SHORT).show();
}
}
}
```
调用方式:
```java
new SaveFileTask(this, "file_name", inputStream).execute();
```
其中,`inputStream`是接口返回的文件流,`file_name`是文件名。以上代码会将文件保存到最近文件夹中,如果该文件夹不存在,则会自动创建。保存成功后会弹出提示。
阅读全文