創建兩個文件selectFile.jsp和readContent.jsp。首先使用selectFile.jsp中的表單輸入存放路徑和將要讀取的文件名,提交後,由readContent.jsp文件負責讀出並顯示在頁面上。運行如圖所示
selectFile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'selectFile.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="readContent.jsp">
請輸入存放文件的路徑:<br>
<input type="text" name="path" /><br>
輸入存在文件名字:<br>
<input type="text" name="file" /><br>
<input type="submit" value="讀取" name="submit">
</form>
</body>
</html>
readContent.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.io.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'readContent.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
String Path = request.getParameter("path");
String file_name = request.getParameter("file");
File d = new File(Path);
File list[] = d.listFiles();
for(int i=0;i<list.length;i++){
if(list[i].getName().equals(file_name)){
out.print(file_name+"文件已找到,爲你讀取中...<br>");
FileReader fr = new FileReader(Path+"\\"+file_name);
%>
<%--在讀取過程中,要判斷以讀取的字符是否已經到了文件的末尾,並且這個字符是不是文件的換行符
即判斷該字符值是否爲13
--%>
<!-- 從文件中讀取一個字符 -->
<%
out.print("內容爲:");
int word = fr.read();
//判斷是否讀到文件結尾
while(word!=-1){
//輸出讀到的數據
out.print((char)word);
//繼續從文件中讀取數據
word = fr.read();
//判斷是否爲換行符
if(word == 13){
//輸出換行標籤
out.print("<br>");
//略過一個字符
fr.skip(1);
//再接着讀取一個字符
word = fr.read();
}
}
fr.close();
}
}
%>
<br><br>
<p><span>已讀取完畢,若無內容則文件不存在,請重新輸入</span>
<br><a href="selectFile.jsp">點此跳轉再次查詢</a>
</body>
</html>
運行結果如圖:
讀取內容
如果碰巧這篇文章對你有所幫助,希望客官點個贊喲,你的點贊就是我更新的動力!
寫入文件在jsp的文件操作(一)有需要可以點擊跳轉!