Servlet中操作文件详解及实例
因为Servlet本来就是一个.Java文件,因此servlet中操作文件和普通java文件操作文件是一样的。
读取文件主要代码:
1
2 |
FileReader f= new FileReader( "f:\\lissdy.txt" ); BufferedReader bw= new BufferedReader(f); |
读出一行数据
1 |
String num=bw.readLine(); |
注意一定要关闭文件流
1 |
bw.close(); |
写文件的方法与之类似,具体代码为:
读取:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 |
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(); } } } |
写入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 |
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(); } } } |