在Web项目中,文件的路径可以指定绝对路径,也可以使用相对路径
绝对路径:D:/Javaweb/Spring05/WebRoot/student.json
相对路径:
示例表述:实现一个功能,在页面输入标题和内容,后将数据保存到文件中。
- 保存到data/
- 每次根据一个标题创建一个文件
本地文件/相对路径:也就是这个意思
后端代码:
package my;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
@WebServlet("/WriFile")
public class WriFile extends HttpServlet
{
public WriFile()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String title = request.getParameter("title");
String content = request.getParameter("content");
System.out.println(title + "**" + content);
String webRootPath = request.getServletContext().getRealPath("/");
System.out.println(webRootPath);
File webRoot = new File(webRootPath);
//在webroot目录下创建data目录(本地文件)
File data = new File(webRoot, "data");
data.mkdirs();
//创建的文件对象
File f = new File(data, title + ".txt");
//f.mkdirs();
System.out.println(f.getAbsolutePath());
//向文件中写入内容
FileOutputStream fstream = new FileOutputStream(f);
try{
fstream.write( content.getBytes( "utf-8" ));
}finally
{
fstream.close();
}
// 返回应答数据
JSONObject jresp = new JSONObject();
jresp.put("error", 0); // 错误码,0表示成功
jresp.put("reason", "OK"); // 错误原因描述, 如果没有错误则提示OK
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
Writer writer = response.getWriter();
writer.write( jresp.toString(2));
writer.close();
}
}
前端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本地文件</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<style>
.main{
width: 600px;
margin: 10px auto;
}
.main .title{
width: 100%;
box-sizing: border-box;
margin: 7px 0px;
}
.main .content{
width: 100%;
height: 150px;
box-sizing: border-box;
margin: 7px 0px;
}
</style>
</head>
<body>
<div class="main">
<input type="text" class="title" placeholder="标题" />
<textarea class="content" placeholder="内容"></textarea>
<button οnclick="save()">提交</button>
</div>
</body>
<script>
function save()
{
var req = { };
req.title = $(".title").val().trim();
req.content = $(".content").val();
console.log(req);
$.ajax({
type:"POST", /*请求类型-POST/GET*/
url:"WriFile", /*服务URI,用相对地址*/
data:req, /*附加请求参数*/
dataType:"json", /*期望服务器返回的数据类型*/
success: function(resp) /*已经将服务器返回的数据转成JS 对象*/
{
if(resp.error==0)
alert("提交成功");
else
alert("出错:"+resp.reason);
},
error: function(jqXHR, textstatus, errorThrown)
{
alert("错误:" +jqXHR.status);
}
});
}
</script>
</html>