当前位置: 代码迷 >> J2SE >> 关于流有关问题
  详细解决方案

关于流有关问题

热度:243   发布时间:2016-04-24 13:21:54.0
关于流问题
try {
  URL conn= new URL("http://www.sina.com/");
  InputStream in=conn.openStream();
  int n=in.available();
  byte[] buf=new byte[1024];
  while((n=in.read(buf))>=0){
  System.out.write(buf,0,n);
  }
  in.close();
  } catch (Exception e) {
  e.printStackTrace(); 
  }

1、如何将in中的数据写入文件呢?
2、如果网页上有中文,如何正确写入文件而不会出现乱码?
谢谢各位指点


------解决方案--------------------
Java code
        try {            fout = new FileOutputStream("d://temp//1.html");            URL conn= new URL("http://www.sina.com/");            InputStream in=conn.openStream();            int n=in.available();            byte[] buf=new byte[1024];            while((n=in.read(buf)) >=0){                System.out.write(buf,0,n);                fout.write(buf);            }            in.close();        } catch (Exception e) {            e.printStackTrace();        } finally {            if(fout != null) {                try {                    fout.close();                } catch (IOException ex) {                    ex.printStackTrace();                }            }        }
------解决方案--------------------
package demo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;

public class IoTest {

/**
* @param args
*/
public static void main(String[] args) {
InputStream is = null;
String str = new String();
FileWriter fw = null;
BufferedWriter bw = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
URL url = new URL("http://www.sina.com/");
is = url.openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
}catch(IOException e1){
e1.printStackTrace();
}
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
try {
fw = new FileWriter("D:\\test\\1.html");
bw = new BufferedWriter(fw);
while((str = br.readLine())!=null){
System.out.println(str);
bw.write(str);
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bw.close();
fw.close();
br.close();
isr.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  相关解决方案