SourceView2利用URLConnection链接一个jsp页面,获得一个文件的inputStream,来在磁盘上创建一个文件,程序是可以运行的但只要是中文就显示乱码,希望大家帮我解决这个问题
SourceView2.java
- import java.io.*;
- import java.net.*;
- import java.util.Map;
- public class SourceView2 {
- public static String convertName(String name){
- name=name.replaceFirst("\"","");
- name=name.replaceFirst("\\[", "");
- name=name.substring(0,name.lastIndexOf("\""));
- return name;
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- try {
- String encoding = "gb2312";
- URL u = new URL(
- "http://localhost:8080//download/download_client.jsp");
- URLConnection uc = u.openConnection();
- String contentType = uc.getContentType();
- int encodingStart = contentType.indexOf("charset=");
- if (encodingStart != -1) {
- encoding = contentType.substring(encodingStart + 8);
- }
- InputStream raw = uc.getInputStream();
- InputStream buffer = new BufferedInputStream(raw);
- Reader r = new InputStreamReader(buffer, encoding);
- Map map = uc.getHeaderFields();
- System.out.println(map.toString());
- System.out.println(map.get("Filename"));
- String filename = map.get("Filename").toString();
- String fileSize=map.get("Size").toString();
- fileSize=SourceView2.convertName(fileSize);
- filename=SourceView2.convertName(filename);
- System.out.println(filename);
- System.out.println(fileSize);
- int size=new Long(fileSize).intValue();
- //在本地磁盘创建数据
- byte[] data=new byte[size];
- buffer.read(data);
- int offset=0;
- int bytesRead=0;
- while(offset<size){
- bytesRead=buffer.read(data,offset,data.length-offset);
- if(bytesRead==-1)
- break;
- offset+=bytesRead;
- }
- buffer.close();
- FileOutputStream fout=new FileOutputStream("e:\\"+filename);
- // BufferedWriter fout=new BufferedWriter(new FileWriter("e:\\aaaa.txt"));
- fout.write(data);
- fout.flush();
- fout.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
jsp页面
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ page import="java.io.*"%>
- <%
- java.io.FileInputStream fileInputStream=null;
- try{
- // 得到文件名字和路径
- String filename = "pdm.xls";
- String filepath = "c:\\download\\";
- File file=new File(filepath+filename);
- // 设置响应头和下载保存的文件名
- response.setContentType("APPLICATION/OCTET-STREAM");
- response.setHeader("Content-Disposition",
- "attachment; filename=\""+filename+ "\"");
- response.setHeader("Filename","\"" + filename + "\"");
- response.setHeader("Size","\"" + file.length() + "\"");
- // 打开指定文件的流信息
- fileInputStream = new java.io.FileInputStream(
- filepath + filename);
- // 写出流信息
- int i;
- while ((i = fileInputStream.read()) != -1) {
- out.write(i);
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- finally{
- fileInputStream.close();
- }
- %>