在写个文件上传程序,提示空指针异常,找不出原因,小郁闷……Struts Problem Report
Struts has detected an unhandled exception: Messages:  
File: java/io/File.java 
Line number: 222 
java.io.File.(File.java:222)
    qiang.action.FileUploadAction.execute(FileUploadAction.java:92)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
//再往下的错误信息省略了吧,看一下java源码FileDao类
package qiang.dao;import java.util.List;import qiang.dto.MyFile;public interface FileDao {
public void addFile() throws Exception;
public List fileList();
public void deleteFile(int i);
}DaoImpl类package qiang.daoImpl;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;import org.apache.struts2.ServletActionContext;import qiang.DatabaseConnection.DatabaseConnection;
import qiang.dao.FileDao;
import qiang.dto.MyFile;
import qiang.dto.User;public class FileDaoImpl implements FileDao {
MyFile mf = new MyFile();
DatabaseConnection dbConn = new DatabaseConnection();

public void addFile() throws Exception{
mf.setNewFileName(null);
long now= new Date().getTime();
User user = new User();
String str = null;
mf.setUploadDir(str);

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date date = new java.util.Date();
String time = simpleDateFormat.format(date);
mf.setUploadTime(time);

String path = ServletActionContext.getServletContext().getRealPath(mf.getUploadDir());
File dir = new File(path);
int index = mf.getFileFileName().lastIndexOf('.');
if(index == -1){
mf.setNewFileName( now+mf.getFileFileName().substring(index));
}else{
mf.setNewFileName(Long.toString(now));
}

String sql="insert into file(oldFileName,newFileName,uploader,description,uploadDate) value ('"+mf.getFileFileName()+"','"+mf.getNewFileName()+"','"+user.getUsername()+"','"+mf.getFileDescription()+"','"+mf.getUploadTime()+"')";
dbConn.exeSqlUpdate(sql);

BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try{
FileInputStream fis = new FileInputStream(mf.getFile());
bis = new BufferedInputStream(fis);

FileOutputStream fos = new FileOutputStream(new File(dir,mf.getNewFileName()));
bos = new BufferedOutputStream(fos);
byte [] buf= new byte[4096];
int len=-1;
while((len = bis.read(buf))!=-1){
bos.write(buf,0,len);
}
}finally{
try{
if(null!=bis){
bis.close();
}
}catch(IOException e){
e.printStackTrace();
}
try{
if(null!=bos){
bos.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
} public List fileList() {
// TODO Auto-generated method stub
return null;
} public void deleteFile(int i) {
// TODO Auto-generated method stub

}}
Action类package test;import qiang.daoImpl.FileDaoImpl;
import qiang.dto.MyFile;
import qiang.dto.User;import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;public class FileUploadAction extends ActionSupport implements ModelDriven<MyFile>{

FileDaoImpl fdi = new FileDaoImpl();
MyFile mf = new MyFile();

public MyFile getModel() {
return mf;
}
public String execute(){
try {
fdi.addFile();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}}
Upload.jsp页面<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<%
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
String user= (String)session.getAttribute("user");
if (user == null) {
%>
<%
response.sendRedirect("login.jsp");
%>
<%
}
%>
<base href="<%=basePath%>">
<title>上传文件</title>
<link href="css/reg.css" rel="stylesheet" type="text/css">
</head>
<body>
<div align="center">
<div class="fileUploadTop" align="center"></div>
<div class="fileUploadBody">
<s:form name="uploadForm" action="upload" method="post" enctype="multipart/form-data">
<table width="40%">
<tr>
&nbsp;
</tr>
<tr>
&nbsp;
</tr>
<tr>
&nbsp;
</tr>
<tr style="text-align: center" align="center">
<h3>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;欢迎使用文件上传功能!
</h3>
</tr>
                        <tr>本系统只是上传不大于2MB的附件
<tr>
<s:file name="file" label="选择文件" />
</tr>
<tr>
<s:textarea name="fileDescription" rows="8" cols="30"
label="文件描述" />
<tr>
<s:submit value="开始上传" />
</tr>
                            <tr><a href="index.jsp">返回主页</a></tr>
</table>
</s:form>
</div>
</div>
        <div align="center">
<div style="background-image:url(img/bottom_bg.png); width:900; height:100">
            <br />
copyright @ 2011 【作者黄海强版权所有】
<br />
联系邮箱:[email protected]
<br />
<br />
</div>
        </div>
</body>
</html>struts.xml配置<action name="upload" class="qiang.action.FileUploadAction">
<result name="success">/fileUploadSuccess.jsp</result>
<result name="input">/fileUpload.jsp</result>
<param name="str">/WEB-INF/uploadFiles</param>
</action>
File类package qiang.dto;import java.io.File;public class MyFile {
private File file; // 上传文件的对象
private String fileFileName; // 上传文件名
private String newFileName;  //
private String fileContentType; // 上传文件的MIME类型
private String fileDescription; // 上传文件描述
private String uploadDir; // 保存上传文件目录,相对于web程序的根目录,具体见struts.xml配置
private String uploadTime;
//get、set方法省略
}package qiang.dto;public class User {
private int id;
private String username;
private String password;
private String repassword;
private String gender;
private String email;
private String regTime;
//get、set方法省略
}
最后还有一个问题,上传完显示在uploadSuccess.jsp页面中,中文名是乱码…………
各种纠结,求指教

解决方案 »

  1.   

     qiang.action.FileUploadAction.execute(FileUploadAction.java:92)把92行标明出来,这样才方便看...
      

  2.   

       File dir = new File(path); 这个是提示异常的那行
      

  3.   


    DAO中的呀,那path是null吗?
      

  4.   

    public File(String pathname)通过将给定路径名字符串转换成抽象路径名来创建一个新 File 实例。如果给定字符串是空字符串,则结果是空的抽象路径名。 参数:
    pathname - 路径名字符串 
    抛出: 
    NullPointerException - 如果 pathname 参数为 nullJDK上说的很清楚,肯定你的参数path是null
      

  5.   

    楼主请参考http://blog.csdn.net/huozhicheng/archive/2011/04/11/6314596.aspx
      

  6.   

    在刚刚异常的地方后边添加了if(!dir.exists()){
    dir.mkdir();
    }
    现在没提示异常了
    提示的是另一句
    int index = mf.getFileFileName().lastIndexOf('.');
    内牛满面