码迷,mamicode.com
首页 > 其他好文 > 详细

Serlvet学习笔记之四—对文件的操作

时间:2016-04-17 06:25:47      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

1.读文件

package com.demo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;

import javax.servlet.http.*;
public class ServletFileTest1 extends HttpServlet {
    public void doGet(HttpServletRequest req,HttpServletResponse res){
        try {
            req.setCharacterEncoding("gb2312");
            res.setContentType("text/html;charset=gb2312");
            PrintWriter pw=res.getWriter();
//创建一个FileReader
            FileReader f=new FileReader("D:\\myCount.txt");
            BufferedReader br=new BufferedReader(f);
            String numVal=br.readLine();
            br.close();     //一定要关闭文件流
            pw.println("从文件中读取的数据是: "+numVal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void doPost(HttpServletRequest req,HttpServletResponse res){
        this.doGet(req, res);
    }
}

2.写文件

package com.demo;
import java.io.*;
import javax.servlet.http.*;
public class ServletFileTest2 extends HttpServlet{
    public void doGet(HttpServletRequest req,HttpServletResponse res){
        try {
            req.setCharacterEncoding("gb2312");
            res.setContentType("text/html;charset=gb2312");
            PrintWriter pw=res.getWriter();
//创建一个FileWriter
            FileWriter f=new FileWriter("D:\\myCount.txt");
            BufferedWriter bw=new BufferedWriter(f);
            bw.write("hello");    //会把原来文件中的信息给删除掉,相当于Linux中的>
            bw.close();
            pw.println("向文件写入信息");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void dopost(HttpServletRequest req,HttpServletResponse res){
        this.doGet(req, res);
    }
}

 

Serlvet学习笔记之四—对文件的操作

标签:

原文地址:http://www.cnblogs.com/zydev/p/5400029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!