Java I/O 體系中,java.io.File 負責路徑抽象與元數據操作;FileReader/Writer、BufferedReader/Writer 提供字符流讀寫;JSP 內置 request.getRealPath() 獲取部署絕對路徑。
CreateDelete.jsp —— 邏輯:路徑存在則刪除,否則創建。
<%@ page import="java.io.*" %>
<%
String path = request.getRealPath("/jsphosting/wenjian");
File file = new File(path, "File.txt");
if (file.exists()) {
file.delete();
out.println(path + "\\File.txt");
%>
<font color="red" size="4">存在</font>, 已完成 <font color="red" size="4">刪除</font>
<%
} else {
file.createNewFile();
out.println(path + "\\File.txt");
%>
<font color="red" size="4">不存在</font>, 已完成 <font color="red" size="4">建立</font>
<%
}
%>
ListFile.jsp —— listFiles() 返回 File[],遍歷輸出文件名。
<%@ page import="java.io.*" %>
<%
String path = request.getRealPath("/jsphosting/wenjian");
File dir = new File(path);
File[] files = dir.listFiles();
%>
在 <font color="red"><%= path %></font> 目錄下的文件有:
<font color="blue">
<ul>
<%
for (File f : files) {
%>
<li><%= f.getName() %></li>
<%
}
%>
</ul>
</font>
ReadAll.jsp —— 使用 FileReader.read() 逐字符讀取,處理換行符(ASCII 13 = CR)。
<%@ page import="java.io.*" %>
<%
String path = request.getRealPath("/jsphosting/wenjian");
FileReader fr = new FileReader(path + "\\File.txt");
int c = fr.read();
while (c != -1) {
out.print((char) c);
c = fr.read();
if (c == 13) { // CR
out.print("<br>");
fr.skip(1); // 跳過 LF (10)
c = fr.read();
}
}
fr.close();
%>
Write.jsp —— FileWriter 寫入多行,隨後用 BufferedReader 逐行回讀顯示。
<%@ page import="java.io.*" %>
<%
String path = request.getRealPath("/jsphosting/wenjian");
FileWriter fw = new FileWriter(path + "\\File.txt");
fw.write("大家好!");
fw.write("祝大家學習jsp愉快!");
fw.write("希望大家能夠深入了解jsp技術!");
fw.close();
%>
<p>寫入文件內容為</p>
<font color="red" size="4">
<%
FileReader fr = new FileReader(path + "\\File.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
out.println(line + "<br>");
br.close();
fr.close();
%>
</font>
try-with-resources 確保流關閉(JSP 1.2+ 支持 JDK 7+ 語法)File.separator 替代硬編碼 \\BufferedReader/Writer)提升性能new InputStreamReader(is, "UTF-8")),避免平台默認編碼差異