将数据存储到SD卡中的问题

时间:2011-06-28 12:14:48

标签: android

我有问题将图像存储到SD卡中,我想要的SD卡中没有显示文件。 这是代码。

package com.sdcard;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class SdcardActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try{
    URL url = new URL ("http://www.coolpctips.com/wp-content/uploads/2011/05/top-30-android-   games.jpg");

    InputStream input = url.openStream();
    try {
        OutputStream output = new FileOutputStream  (Environment.getExternalStorageDirectory()+"/top-30-android-games.jpg");
        try {
            int aReasonableSize = 10;
            byte[] buffer = new byte[aReasonableSize];
            int bytesRead = 0;
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, buffer.length);
            }
        } finally {
            output.close();
        }
    } finally {
        input.close();
    }
    }catch (Exception e) {
        e.printStackTrace();
    }
}}

3 个答案:

答案 0 :(得分:2)

在您的代码中添加以下行:

catch (Exception e) {
    e.printStackTrace();
}

你会注意到网址格式错误的异常。添加有关您想要实现的目标的更多信息,以便我可以写出更好的答案。


评论中的例外情况可能与Android中的某种错误有关: http://code.google.com/p/android/issues/detail?id=2764。您可以尝试使用此解决方案:Android java.net.UnknownHostException: Host is unresolved (strategy question)或提供IP地址而不是DNS。

您已经测试了代码:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try{
    URL url = new URL ("http://www.coolpctips.com/wp-content/uploads/2011/05/top-30-android-games.jpg");
    InputStream input = url.openStream();
    try {
        OutputStream output = new FileOutputStream  (Environment.getExternalStorageDirectory()+"/top-30-android-games.jpg");
        int aReasonableSize = 1000;
        byte[] buffer = new byte[aReasonableSize];
        int bytesRead = 0;;
        try {
            while ((bytesRead = input.read(buffer)) > 0) {
                output.write(buffer, 0, bytesRead);
            }
        } finally {
            output.close();
        }
    } finally {
        input.close();
    }
    }catch (Exception e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

你应该使用 Environment.getExternalStorageDirectory()而不是 mnt / sdcard /

OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/myImage.png");

答案 2 :(得分:0)

您的问题是您在Android设备中引用主机本地文件系统。 C:\不是android知道如何解释的路径。

将其托管在本地网络服务器上,然后使用http://192.168.0.100/your/url/image.png

之类的内容