在内部存储android上下载文件时出错

时间:2012-12-12 19:12:14

标签: android file logging storage internal

由于我认为下载非常简单,因此当我尝试从Internet下载xml文件并将其保存在内部存储器中时遇到错误。我使用内部存储器,因为我在三星galaxy s3上测试我的应用程序。

以下是下载程序的代码。它实际上是一个从活动

调用的线程
public class DownloaderThread extends Thread
{
    private static final int DOWNLOAD_BUFFER_SIZE = 4096;
    Context context;
    private String downloadUrl = "some address";

    public void run()
    {
            URL url;
            URLConnection conn;
            String fileName;
            BufferedInputStream inStream;
            BufferedOutputStream outStream;
            File outFile;
            FileOutputStream fileStream;

            try
            {
                    url = new URL(downloadUrl);
                    conn = url.openConnection();
                    conn.setUseCaches(false);
                    fileName = "file.xml";

                    Log.v("XML", "Download Started");

                    // start download
                    inStream = new BufferedInputStream(conn.getInputStream());
                    outFile = new File(context.getFilesDir() + "/" + fileName);
                    fileStream = new FileOutputStream(outFile);
                    outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
                    byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
                    int bytesRead = 0;
                    while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
                    {
                            outStream.write(data, 0, bytesRead);
                    }

                    outStream.close();
                    fileStream.close();
                    inStream.close();

                    if(isInterrupted())
                    {
                            outFile.delete();
                    }
                    else
                    {
                            Log.v("XML","Download Finished");
                            Log.v("PATH","File is stored in direcotry:" + outFile.getAbsolutePath().toString());
                    }
            }
            catch(MalformedURLException e)
            {
                e.printStackTrace();
                Log.v("Error",e.toString());

            }
            catch(FileNotFoundException e)
            {
                e.printStackTrace();
                Log.v("Error",e.toString());
            }
            catch(Exception e)
            {
                e.printStackTrace();
                Log.v("Error",e.toString());
            }
    }

这是调用线程的代码:

public boolean onOptionsItemSelected(MenuItem item) {
     ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
     android.net.NetworkInfo datac = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
     if ( item.getItemId() == DOWNLOAD_XML_MENU_ITEM ) {
            if ((wifi != null & datac != null) && (wifi.isConnected() | datac.isConnected())) 
            {
                downloaderThread = new DownloaderThread();
                downloaderThread.start();
            }
            else 
            {
                displayConnectionAlert();
            }
        }
        return true;
    }

我收到的错误是:    标记跟踪 - 没有这样的文件和目录 并且在下载日志后,我在outFile的路径上获得NullPointerException。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您正在使用永远未分配值的Context引用,因此是NPE。

Context context; // never initialised anywhere, thus null

由于所有变量都用于解析context.getFilesDir(),我建议你只需为你的线程类创建一个构造函数,它将路径作为参数;即:

public DownloaderThread(String targetDir) { /* implement here */ }

或者,您实际上可以传入Context实例,但只需确保它是应用程序上下文(而不是Activity)以避免潜在的内存泄漏。

答案 1 :(得分:0)

除其他外,您需要致电conn.connect()。只是打开连接不会连接到主机。

此外,快速提示:当您创建文件时,使用new File(getFilesDir(), fileName)而不是进行字符串连接更容易和(恕我直言)。