<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>输入需保存的内容</title>
<meta http-equiv="content-type" content="text/html; charset=GBK">
</head>
<body>
<form action="fileoperate.jsp" method="post">
文件名称:<input type="text" name="filename"/><br/>
文件内容:<textarea name="filecontent" cols="30" rows="3"></textarea><br/>
<input type="submit" value="保存"/>
<input type="reset" value="重置"/>
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page contentType="text/html; charset=GBK" %>
<%@page import="java.io.File"%>
<%@page import="java.io.PrintStream"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.FileInputStream"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件保存与读取</title>
</head>
<body>
<%
request.setCharacterEncoding("GBK");
String name = request.getParameter("filename");
String content = request.getParameter("filecontent");
String filename = this.getServletContext().getRealPath("/") + "file" + File.separator + name;
File file = new File(filename);
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();//如果父文件夹不存在则创建文件夹
}
/************************存文件 start ************************/
PrintStream ps = null;
ps = new PrintStream(new FileOutputStream(file));
ps.println(content);
ps.close();
/************************存文件 end ************************/
%>
<%
/************************读文件 start ************************/
Scanner scan = new Scanner(new FileInputStream(file));
scan.useDelimiter("\n");
StringBuffer buffer = new StringBuffer();
while(scan.hasNext()){
buffer.append(scan.next()).append("<br/>");
}
scan.close();
/************************读文件 end ************************/
%>
<%=buffer %>
</body>
</html>