读文件,下载文件
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();
}
}
}