android应用程序的写问题
下面是从web下载图像后写入文件的代码。但不知何故,它只是在写入文件流时卡住了。毫无例外。当循环显示强制关闭弹出窗口时,它将保持打开状态。10次中有2次或3次android应用程序的写问题,android,fileoutputstream,Android,Fileoutputstream,下面是从web下载图像后写入文件的代码。但不知何故,它只是在写入文件流时卡住了。毫无例外。当循环显示强制关闭弹出窗口时,它将保持打开状态。10次中有2次或3次 private void saveImage(String fullPath) { File imgFile = new File(fullPath); try { if(imgFile.exists()) imgFile.delete(); URL url = new URL(this.fileURL);
private void saveImage(String fullPath) {
File imgFile = new File(fullPath);
try {
if(imgFile.exists()) imgFile.delete();
URL url = new URL(this.fileURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream in = httpConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(imgFile);
int n = 0;
while((n = in.read()) != -1) {
fos.write(n);
}
fos.flush();
fos.close();
in.close();
}
catch(IOException e) {
imgFile.delete();
Log.d("IOException Thrown", e.toString());
}
}
当我检查写入的文件时,它总是在写入到4576字节时被卡住。(原始图像大小超过150k)
有人能在这个问题上帮助我吗?嗨,Juniano回答你的第二个问题,是的,你可以使用while循环,但你还需要两件事
private void saveImage(String fullPath) {
File imgFile = new File(fullPath);
try {
if(imgFile.exists()) imgFile.delete();
/** URL url = new URL(this.fileURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream in = httpConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(imgFile);
int n = 0;
while((n = in.read()) != -1) {
fos.write(n);
}
fos.flush();
fos.close();
in.close();***/
FileOutputStream fos = new FileOutputStream(imgFile);
URL url = new URL(this.fileUR);
Object content = url.getContent();
InputStream in = (InputStream) content;
Bitmap bitmap = BitmapFactory.decodeStream(in);
bitmap.compress(CompressFormat.JPEG,80, fos);
fos.flush();
fos.close();
in.close();
}
catch(IOException e) {
imgFile.delete();
Log.d("IOException Thrown", e.toString());
}
}
URL url = new URL(this.fileURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
InputStream in = httpConnection.getInputStream();
BufferedInputStream myBis = new BufferedInputStream(in);
1) 创建ByteArrayBuffer以存储输入流
ByteArrayBuffer myBABuffer = new ByteArrayBuffer(50);
int current = 0;
while ((current = myBis.read()) != -1) {
myBABuffer.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(imgFile);
2) 使用存储的字节创建映像
fos.write(myBABuffer.toByteArray());
fos.flush();
fos.close();
in.close();
Jorgesys只需更改位图中的压缩格式和质量。压缩(,)函数。=)谢谢在我切换代码后,我对它进行了几次测试。到目前为止,看起来还不错。你认为我的代码有什么问题?我不应该用“while”循环来写流吗?再次谢谢你,Jorgesys。。我用了你的第一个建议,效果很好。嗨,Jorgesys。您是否解决了“流程不好”的问题?我发现了你的问题,之后没有更新。我也有同样的问题,但能找到解决办法。我知道这不是问你这个问题的好地方,但这是我唯一可以与你联系的地方。:)嗨,Juniano为什么你会遇到“进程不好”的异常,你是在android小部件中使用这段代码的吗???