前面咱们说过
ServletContext
表示的是web容器中的上下文,下面咱们也是用到ServletContext
中的方法读取文件java
咱们知道当咱们将项目部署到
Tomcat
服务器中时,项目中的文件路径其实就是在Tomcat中的文件路径,全部的项目都是存储在webapps下的,咱们能够看到webaapps下有两个文件夹(WEB-INF,META-INF)
,这两个其实就是项目中webRoot
下的两个文件夹。web
public String getRealPath(String path)
为给定虚拟路径返回包含实际路径的String
//获取ServletContext的对象 ServletContext context = this.getServletContext(); //context.getRealPath("/")获取项目的根目录的绝对路径(webRoot的绝对路径) //获得了webRoot的绝对路径,下面只要再接着写其余文件的路径便可 File file = new File(context.getRealPath("/") + "\\WEB-INF\\lib\\file.txt"); if (file.exists()) { System.out.println("文件存在"); } else { System.out.println("文件不存在,如今咱们建立一个"); try { file.createNewFile();// 建立一个新的文件 } catch (IOException e) { e.printStackTrace(); } }
InputStream getResourceAsStream(String path)
根据传入的路径文件,返回一个InputStream
对象
// 第一个"/"是表示webRoot的根目录,经过这个函数能够不用指定绝对路径就能够构造一个输入字节流 InputStream stream = context .getResourceAsStream("/WEB-INF/lib/file.txt"); // 经过InputStreamReader将字节流转换为字符流,而后建立缓冲字符流读取文件 BufferedReader reader = new BufferedReader( new InputStreamReader(stream)); try { System.out.println(reader.readLine()); } catch (IOException e) { System.out.println("文件没有成功读取"); e.printStackTrace(); }
注意:这个函数中的path传入的第一个
"/"
就表示根目录,在eclipse
项目中表示webRoot的绝对路径,在Tomcat
下的webapps表示项目名称的绝对路径,所以在下面的WEB-INF,META-INF文件夹下的文件只须要在后面继续添加便可服务器
前面咱们获取的
webRoot
下的文件路径,可是若是咱们想要获取src
下的文件,那么咱们要如何获取呢。app
咱们仔细看看
Tomcat
下的文件,能够发如今每个WEB-INF下都有一个classes
,这个就是至关于Tomcat下的src,所以咱们利用上面获得的路径稍加修改就能够轻易的获得其中的文件路径eclipse
下面咱们读取
src
文件夹下的file.txt
中的内容,代码以下:webapp
// 获取ServletContext对象 ServletContext context = this.getServletContext(); // 这个是获取项目下的src文件夹下的file.txt文件 File file = new File(context.getRealPath("/") + "\\WEB-INF\\classes\\file.txt"); BufferedReader reader = null; if (file.exists()) { System.out.println("文件存在,如今能够读取"); try { // 建立缓冲流对象,实现读取文件 reader = new BufferedReader(new FileReader(file)); try { // 输出第一行内容 System.out.println(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { System.out.println("文件不存在"); } finally { if (reader != null) { try { reader.close(); // 若是reader不是空,就关闭 } catch (IOException e) { System.out.println("文件关闭失败"); } } } } else { System.out.println("文件不存在,如今开始建立一个"); try { file.createNewFile();// 建立一个 } catch (IOException e) { System.out.println("没有建立成功"); } }