servlet在tomcat中读取文件问题

作者:王奎            此文章也同时发布于我的博客:www.marksaas.com

今天看到一篇文章想读取类路径中的一个txt文件,并用servlet输出到浏览器,在web环境下读取文件一般会出各种问题,请参看我以前写的文章tomcat下获取项目绝对路径问题

这上面讲解了如何获取项目绝对路径和其他一些问题。。

下面进入今天的主题吧。

直接上代码

                response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		String fileName="content.txt";
		String realPath=request.getRealPath(fileName);
		File file=new File(realPath);
		if(file.exists()){
			FileReader reader=new FileReader(file);
			BufferedReader bufferReader=new BufferedReader(reader);
			String line=null;
			while(null!=(line=bufferReader.readLine())){
				out.print(line);
			}
		}else{
			out.println("file is not exist");
		}

咋一看这段代码没什么问题,得到的也是项目的绝对路径,但是部署到服务器连接时问题暴漏出来了,file is not exist。经过测试原来在得到realPath时就出现了问题,没能拿到文件的绝对路径,,把文件放在类路径下不能被访问到,但是放到项目根目录下可以被访问到(WEB-INF下),放到类路径下也可以被访问到,

代码如下:

	response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out=response.getWriter();
		String fileName="WEB-INF\\classes\\content.txt";
		String realPath=this.getServletContext().getRealPath("/")+fileName;
		File file=new File(realPath);
		if(file.exists()){
			FileReader reader=new FileReader(file);
			BufferedReader bufferReader=new BufferedReader(reader);
			String line=null;
			while(null!=(line=bufferReader.readLine())){
				out.print(line);
			}
		}else{
			out.println("file is not exist");
		}
		
就是得手动添加一些文件目录,在网上搜没有找到好的函数用,,这点如果有人知道,欢迎探讨。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值