当我认为下载非常简单时,当我尝试从 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。任何想法为什么?