tomcat下载文件,报告空指针异常,无法下载文件

qq_33573039 2016-01-18 10:02:27
菜鸟跟mars的视频,自学android中,但是今天这段视频老是报告空指针异常,把mars的源代码直接用项目导入可以使用,但是把代码复制到自己新建的项目中就报空指针异常,新手分不多,还望指教!根据logcat输出内容,HttpDownloader里面的76行出错,接着导致Activity里面的42行代码也出错,代码如下:

package com.victor.e08_download;

import com.victor.e08_utils.HttpDownloader;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity {
private Button txtButton;
private Button mp3Button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txtButton = (Button)findViewById(R.id.bt_Text);
mp3Button = (Button)findViewById(R.id.bt_Mp3);
txtButton.setOnClickListener(new DownloadTxtListener());
mp3Button.setOnClickListener(new DownloadMp3Listener());
}
class DownloadTxtListener implements OnClickListener{

@Override
public void onClick(View v) {
HttpDownloader httpDownloader = new HttpDownloader();
String lrc = httpDownloader.download("http://192.168.1.107:8080/voa1500/a1.lrc");
System.out.println(lrc);
}

}
class DownloadMp3Listener implements OnClickListener{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownloader httpDownloader = new HttpDownloader();
int result = httpDownloader.downFile("http://192.168.2.102:8080/1.doc", "voa/", "voa01");
System.out.println(result);
}

}

}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.victor.e08_utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;



public class HttpDownloader {
private URL url = null;

/**
* 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
* 1.创建一个URL对象
* 2.通过URL对象,创建一个HttpURLConnection对象
* 3.得到InputStram
* 4.从InputStream当中读取数据
* @param urlStr
* @return
*/
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
// 创建一个URL对象
url = new URL(urlStr);
// 创建一个Http连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 使用IO流读取数据
buffer = new BufferedReader(new InputStreamReader(urlConn
.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}

/**
* 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
*/
public int downFile(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();

if (fileUtils.isFileExist(path + fileName)) {
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}

/**
* 根据URL得到输入流
*
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConn.getInputStream();
return inputStream;
}
}


---------------------------------------------------------------------------------------------------------------------------------------------------------

package com.victor.e08_utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils {
private String SDPATH;

public String getSDPATH() {
return SDPATH;
}
public FileUtils() {
//得到当前外部存储设备的目录
// /SDCARD
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在SD卡上创建文件
*
* @throws IOException
*/
public File creatSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}

/**
* 在SD卡上创建目录
*
* @param dirName
*/
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdir();
return dir;
}

/**
* 判断SD卡上的文件夹是否存在
*/
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}

/**
* 将一个InputStream里面的数据写入到SD卡中
*/
public File write2SDFromInput(String path,String fileName,InputStream input){
File file = null;
OutputStream output = null;
try{
creatSDDir(path);
file = creatSDFile(path + fileName);
output = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while((input.read(buffer)) != -1){
output.write(buffer);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return file;
}

}
...全文
260 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
柒加伊 2016-01-21
  • 打赏
  • 举报
回复
引用 6 楼 qq_33573039 的回复:
[quote=引用 4 楼 woshiyyshow 的回复:] https://img-bbs.csdn.net/upload/201601/19/1453170659_440719.png 检查一下连接是否开启了. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); if (urlConn .getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else { System.out.println("###" + urlConn .getResponseCode()); } 加上上面的判断验证一下是否与服务器连通.
handler的问题发现了,原来没有发送消息,加上sendmessage语句后已经正常![/quote] 访问网络得放在一步线程处理, 如果是这个问题, logcat里面是有错误提示的. 下次一定要仔细分析logcat里面的信息, 对你以后查找BUG是有很大帮助的.
qq_33573039 2016-01-20
  • 打赏
  • 举报
回复
引用 4 楼 woshiyyshow 的回复:
https://img-bbs.csdn.net/upload/201601/19/1453170659_440719.png 检查一下连接是否开启了. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); if (urlConn .getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else { System.out.println("###" + urlConn .getResponseCode()); } 加上上面的判断验证一下是否与服务器连通.
handler的问题发现了,原来没有发送消息,加上sendmessage语句后已经正常!
qq_33573039 2016-01-20
  • 打赏
  • 举报
回复
引用 4 楼 woshiyyshow 的回复:
https://img-bbs.csdn.net/upload/201601/19/1453170659_440719.png 检查一下连接是否开启了. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); if (urlConn .getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else { System.out.println("###" + urlConn .getResponseCode()); } 加上上面的判断验证一下是否与服务器连通.
引用 4 楼 woshiyyshow 的回复:
https://img-bbs.csdn.net/upload/201601/19/1453170659_440719.png 检查一下连接是否开启了. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); if (urlConn .getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else { System.out.println("###" + urlConn .getResponseCode()); } 加上上面的判断验证一下是否与服务器连通.
突然发现问题所在了,模拟器用的是4.2的,不允许在主线程访问网络,今天新建线程去执行下载的代码,可以正常下载了。非常感谢你的回答,分就给你了,虽然不多,但是也算是一种感谢吧。但是今天小弟又遇到了一个新的问题,项目目的是将一张网络上的图片显示到手机的ImageView空间里面。思路是用新的线程将图片获取到Bitmap里面后,用handler传过去。但是不知道关于handler的那块代码是不是有错误(附在下面),始终没有显示成功。 新线程里面的run()方法代码如下:
try {
				address = mEtAddress.getText().toString().trim();
				if("".equals(address)){
					Toast.makeText(MainActivity.this, "图片地址不允许为空", Toast.LENGTH_SHORT).show();
				}
				Bitmap bitmap = ImageUtil.getImage(address);
				System.out.println(bitmap.toString());
				Message msg =handler.obtainMessage();
				msg.obj = bitmap;
			} catch (Exception e) {
				e.printStackTrace();
			}
---------------------------------------------------------------------------------------------------------------------------------------------------------------- handler类里面的 handlemessage()方法如下
public void handleMessage(Message msg) {
			Bitmap bitmap = (Bitmap)msg.obj;
			mIvView.setImageBitmap(bitmap);
		}
		
qq_33573039 2016-01-19
  • 打赏
  • 举报
回复
引用 2 楼 woshiyyshow 的回复:
/** * 根据URL得到输入流 * * @param urlStr * @return * @throws MalformedURLException * @throws IOException */ public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConn.getInputStream(); return inputStream; } 76行是inputStream为空, 那就看上面的方法里面的inputStream是不是返回的就是空. 如果返回的是空, 那你就看看你下载文件的路径是否正确. 你先用浏览器看一下http://192.168.2.102:8080/1.doc你这个路径能不能看到文件. 怎么感觉好像是你文件路径的问题.
debug了一下,断点设置在96行,点击F5,提示Source not found(不知何故,还望指教)如下图: 后续将tomcat运行后,用IE直接输入http://192.168.2.102:8080/1.doc 这个路径,IE自动下载了1.doc文件,证明路径应该是能访问的。
柒加伊 2016-01-19
  • 打赏
  • 举报
回复
/** * 根据URL得到输入流 * * @param urlStr * @return * @throws MalformedURLException * @throws IOException */ public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConn.getInputStream(); return inputStream; } 76行是inputStream为空, 那就看上面的方法里面的inputStream是不是返回的就是空. 如果返回的是空, 那你就看看你下载文件的路径是否正确. 你先用浏览器看一下http://192.168.2.102:8080/1.doc你这个路径能不能看到文件. 怎么感觉好像是你文件路径的问题.
qq_33573039 2016-01-19
  • 打赏
  • 举报
回复
菜鸟一个,直接导入mars原工程项目就能下载成功,但是自己敲出代码后运行就无法下载文件,还请大神指点。
柒加伊 2016-01-19
  • 打赏
  • 举报
回复
https://img-bbs.csdn.net/upload/201601/19/1453170659_440719.png 检查一下连接是否开启了. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); if (urlConn .getResponseCode() == HttpURLConnection.HTTP_OK) { return true; } else { System.out.println("###" + urlConn .getResponseCode()); } 加上上面的判断验证一下是否与服务器连通.

80,490

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧