我从api获取数据,我想用这些数据写/保存一些文件。这是我的代码
try
{
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/incubate_files");
if (!myDir.exists()) myDir.mkdirs();
File file = new File(Environment.getExternalStorageDirectory().getPath()+File.separator+"/incubate_files/", "messageId_"+messageId+"."+ext);
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = content.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
output.close();
output.flush();
content.close();
}
catch (Exception e)
{
e.printStackTrace();
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
没有例外,只有空文件
谢谢!
更新
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
Log.d(app.TAG,"Cadena: "+builder.toString());
InputStream is = new ByteArrayInputStream(builder.toString().getBytes());
我将我的InputStream白色改为api的内容。 api返回了很多字符。图像实际存在于服务器中,我可以看到它。
现在该文件有一些字节,但我无法在手机中看到
api响应是二进制的
答案 0 :(得分:0)
您需要使用连接对象中的getInputStream
方法并将数据保存到File
。例如:
InputStream input = connection.getInputStream();
File file = new File("download_directory_path", "file_name");
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int bufferLength = 0;
while((bufferLength = input.read(buffer)) != -1)
output.write(buffer, 0, bufferLength);
然后终于close()
您的output
和input
个流。
写完后,file
指向下载的文件。