文件读取操作

    读文件,下载文件

package com;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ExpServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{		
		//下载Xml文件
		String filePath ="D:\\wfxw01.xml";
		if(!"".equals(filePath.trim()))
		{
			//response.setContentType("text/html");
			response.setHeader("Content-disposition", "attachment;filename=\""+ filePath+ "\";");
					
			FileInputStream fileInputStream  = null;
			BufferedOutputStream out  = null;
			try
			{
			   fileInputStream = new FileInputStream(filePath);
			   out = new BufferedOutputStream(response.getOutputStream());
			   int i = 0;
			   while ((i = fileInputStream.read()) != -1) 
			   {
			    out.write(i);
			   }
			
			}catch(Exception ex)
			{
				ex.printStackTrace();
				System.out.println("输出Xml有误");
			}finally
			{
			   if(fileInputStream != null){try{fileInputStream.close();}catch(Exception fx){fx.printStackTrace();}}
			   if(out != null){try{out.close();}catch(Exception fx){fx.printStackTrace();}}
			}
		}
	}
}

    读取一个文件内容,重新生成一个文件

package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainTest {
	public static void main(String[] args) {
        try {  
            FileWriter fileWriter=new FileWriter("D:\\wfxw01.xml");  
            BufferedWriter bfW=new BufferedWriter(fileWriter);
            /*----------------------------------------*/  
            FileReader fileReader=new FileReader("D:\\wfxw.xml");  
            BufferedReader bfR=new BufferedReader(fileReader);  
            String str="";  
            int i=0;
            do{
                str=bfR.readLine();
                if(i==0)
                {
                	str="<?xml version=\"1.0\" encoding=\"GBK\"?>";
                }

                bfW.write(str==null?"":str);  
                bfW.newLine();
                i++;
            }while(str!=null);  
            fileReader.close();  
            bfR.close(); 
            /*----------------------------------------*/
            bfW.flush();  
            bfW.close();  
            fileWriter.close(); 
        } catch (IOException e) {            
            e.printStackTrace();  
        } 
	}
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值