Java获取Web服务器文件

来源:互联网 发布:网站用什么源码好 编辑:程序博客网 时间:2024/04/28 00:30

如果获取的是服务器上某个目录下的有关文件,就相对比较容易,可以设定死绝对目录,但是如果不能设定死绝对目录,也不确定web服务器的安装目录,可以考虑如下两种方式:

  1. 方法一:先获取web服务器当前绝对位置,然后拼接相对目录

考虑到java web项目一般会采用strust2来做,所以可以使用ServletActionContext.getServletContext().getRealPath("")来获取当前的web服务器绝对路径。再拼接相对位置即可,总的程序示例如下:

public InputStream getFileStream() throws Exception{    System.out.println(filename);    String realPath = ServletActionContext.getServletContext().getRealPath("");    System.out.println("realPath:"+realPath);    return new FileInputStream(realPath+filename);}
  1. 方法二:通过webURL地址才获取文件

因为不管web服务器安装在什么位置,其对外显示的URL地址总是不变的,如http://xx.xx.xx.xx/xx 那么要返回http://xx.xx.xx.xx/xx/xx.doc 文件的话,可以采用如下方式,没有做过实验,不过类似于网络爬虫中的文件获取。

URL url = new URL(urlString); URLConnection conn = url.openConnection();  BufferedReader reader = new BufferedReader(new InputStreamReader(conn. getInputStream()));  

获取网络流后再返回文件流1

0 0
原创粉丝点击