雖然現代 Web 開發推薦前後端分離,但維護舊系統或快速原型時,JSP 直接操作本地文件仍有需求。本文提供一個功能完整的 JSP 文件管理頁面代碼,涵蓋目錄瀏覽、ZIP/RAR 解壓、系統命令執行、服務管理、文件系統信息獲取等核心功能,可作為參考庫直接復用。
public static String exec(String cmd, Writer out) throws IOException {
Process p = Runtime.getRuntime().exec(cmd);
InputStream is = p.getInputStream();
byte[] buf = new byte[cmd.length() * 10];
int len; StringBuffer sb = new StringBuffer();
while ((len = is.read(buf)) != -1) {
String s = new String(buf, 0, len);
if (out != null) { out.write(s); out.flush(); }
sb.append(s);
}
is.close();
return sb.toString();
}
public String unzip(File file, File dir) throws IOException {
if (!file.getName().toLowerCase().endsWith(".zip")) return "非 ZIP 文件";
ZipFile zf = new ZipFile(file);
Enumeration<? extends ZipEntry> entries = zf.entries();
StringBuffer result = new StringBuffer();
while (entries.hasMoreElements()) {
ZipEntry ze = entries.nextElement();
File target = new File(dir, ze.getName());
if (ze.isDirectory()) { target.mkdirs(); continue; }
target.getParentFile().mkdirs();
try (InputStream is = zf.getInputStream(ze);
FileOutputStream fos = new FileOutputStream(target)) {
byte[] buf = new byte[8192]; int len;
while ((len = is.read(buf)) != -1) fos.write(buf, 0, len);
}
result.append(ze.getName()).append("<br/>");
}
zf.close();
return result.append("全部完成").toString();
}
// 查找 UnRAR.exe:Program Files / D盤 / WebApp 根目錄
// 執行:unrar x -o+ -p- <rar文件> <目標目錄>
// 解析輸出判斷成功/失敗
FileSystemView 獲取圖標、顯示名稱、根目錄ShellFolder (Sun 內部類) 獲取 Windows 殼擴展信息sc query / net start 輸出獲取服務狀態頁面頂部導入大量包(java.io, java.util.zip, javax.swing, sun.awt.shell 等),主體為 JSP 腳本片段(<%! ... %> 聲明方法,<% ... %> 執行邏輯),混合 HTML 輸出。屬單文件大雜燒風格,實際項目請拆分為 Controller + Service + JSP/前端模板。