Struts2文件下载找不到输入流异常

先发异常

Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action

这个异常是因为在sturts.xml中配置的输入流没有找到或者得不到,或者为Null,总之就是获取不到,原因是因为我在Action中获取流的路径写的不正确,导致没有获取到流,改了路径就OK了!

Action中获取文件流

//附件下载需要的流
    public InputStream getInputStream() throws Exception{
     //这样获取到的流位null,估计是路径写的不正确
//return ServletActionContext.getServletContext().getResourceAsStream("C:/Users/Administrator/Desktop/test.txt"); File f = new File("C:/Users/Administrator/Desktop/test.txt"); InputStream stream = new FileInputStream(f); return stream; }

下次注意!

来看一发getResourceAsStream:

Java中getResourceAsStream的用法

首先,Java中的getResourceAsStream有以下几种:
1. Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从

ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。

2. Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由

ClassLoader获取资源。

3. ServletContext. getResourceAsStream(String path):默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,

当然这和具体的容器实现有关。

4. Jsp下的application内置对象就是上面的ServletContext的一种实现。

其次,getResourceAsStream 用法大致有以下几种:

第一: 要加载的文件和.class文件在同一目录下,例如:com.x.y 下有类me.class ,同时有资源文件myfile.xml

那么,应该有如下代码:

me.class.getResourceAsStream("myfile.xml");

第二:在me.class目录的子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.y.file 目录下有资源文件myfile.xml

那么,应该有如下代码:

me.class.getResourceAsStream("file/myfile.xml");

第三:不在me.class目录下,也不在子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.file 目录下有资源文件myfile.xml

那么,应该有如下代码:

me.class.getResourceAsStream("/com/x/file/myfile.xml");

总结一下,可能只是两种写法

第一:前面有 “   / ”

“ / ”代表了工程的根目录,例如工程名叫做myproject,“ / ”代表了myproject

me.class.getResourceAsStream("/com/x/file/myfile.xml");

第二:前面没有 “   / ”

代表当前类的目录

me.class.getResourceAsStream("myfile.xml");

me.class.getResourceAsStream("file/myfile.xml");

声明:蓝色字体部分转载自:http://www.cnblogs.com/javayuer/archive/2011/01/02/1924192.html

原文地址:https://www.cnblogs.com/moxuyou/p/5508330.html