zoukankan      html  css  js  c++  java
  • Serlvet学习笔记之四—对文件的操作

    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");    //会把原来文件中的信息给删除掉,相当于>
                bw.close();
                pw.println("向文件写入信息");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void dopost(HttpServletRequest req,HttpServletResponse res){
            this.doGet(req, res);
        }
    }
  • 相关阅读:
    一道题DP
    BZOJ 3155: Preprefix sum
    BZOJ:3209: 花神的数论题
    TJU 4087. box
    BZOJ1192: [HNOI2006]鬼谷子的钱袋
    概率DP
    Codeforces Round #253 (Div. 2) D题
    二维树状数组
    Codeforces Round #250 (Div. 2)
    莫比乌斯函数
  • 原文地址:https://www.cnblogs.com/zydev/p/5400029.html
Copyright © 2011-2022 走看看