<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>Read Text File in JSP</title></head><body><% String filePath = "/WEB-INF/data/file.txt"; // 相对路径,文件放在WEB-INF目录下 String realPath = application.getRealPath(filePath); // 获取文件的真实路径 BufferedReader reader = new BufferedReader(new FileReader(realPath)); String line = null; while ((line = reader.readLine()) != null) { out.println(line); // 输出文件内容到浏览器 } reader.close();%></body></html>优化这段代码
时间: 2024-04-26 15:20:15 浏览: 148
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Read Text File in JSP</title>
</head>
<body>
<%
String filePath = "/WEB-INF/data/file.txt"; // 相对路径,文件放在WEB-INF目录下
String realPath = application.getRealPath(filePath); // 获取文件的真实路径
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), "UTF-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
out.println(line); // 输出文件内容到浏览器
}
} catch (IOException e) {
e.printStackTrace();
}
%>
</body>
</html>
优化点:
1. 使用 try-with-resources 简化代码;
2. 使用 InputStreamReader 指定编码,避免文件编码与 JSP 页面编码不一致导致乱码;
3. 添加异常处理,避免出现异常导致页面无法正常加载。
阅读全文