Servlet中操作文件詳解及實例
因為Servlet本來就是一個.Java文件,因此servlet中操作文件和普通java文件操作文件是一樣的。
讀取文件主要代碼:
FileReader f=new FileReader("f:\\lissdy.txt");
BufferedReader bw=new BufferedReader(f);
讀出一行數據
String num=bw.readLine();
注意一定要關閉文件流
寫文件的方法與之類似,具體代碼為:
讀?。?br />
package com.lissdy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@SuppressWarnings("serial")
public class ReadFile extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try {
res.setContentType("text/html;charset=gbk");
PrintWriter pw=res.getWriter();
FileReader f=new FileReader("d:\\lissdy.txt");
BufferedReader bw=new BufferedReader(f);
String num=bw.readLine();
bw.close();
pw.println("從文件中讀取的數據是:"+num);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
寫入:
package com.lissdy;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@SuppressWarnings("serial")
public class WriteFile extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try {
res.setContentType("text/html;charset=gbk");
PrintWriter pw=res.getWriter();
//從內存到磁盤流動為寫(輸出流)
//從磁盤文件到內存流動為讀(輸入流)
FileWriter f=new FileWriter("d:\\lissdy.txt");
BufferedWriter bw=new BufferedWriter(f);
bw.write("試一試文件怎么寫");
pw.println("向文件寫入數據");
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!