Servlet总结二(文件路径)
前言
读取WebRoot文件下的文件
//获取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();
}
}
// 第一个"/"是表示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();
}
读取src下的class文件
// 获取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("没有创建成功");
}
}