1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.OutputStream; 8 import java.io.OutputStreamWriter; 9 import java.net.MalformedURLException; 10 import java.net.URL; 11 import java.net.URLConnection; 12 13 public class javaTest2 extends Thread { 14 15 public static void main(String[] args) throws IOException { 16 URL url=new URL("http://www.baidu.com"); 17 InputStream is=url.openStream(); 18 //将字节流转换为字符流 19 InputStreamReader isr=new InputStreamReader(is,"gbk"); 20 //字符流输入添加缓冲 21 BufferedReader bfr=new BufferedReader(isr); 22 23 String data=bfr.readLine(); 24 System.out.println(data); 25 26 27 URLConnection urlc=url.openConnection(); 28 InputStream is1=urlc.getInputStream(); 29 //将字节流转换为字符流 30 InputStreamReader isr1=new InputStreamReader(is1,"gbk"); 31 //字符流输入添加缓冲 32 BufferedReader bfr1=new BufferedReader(isr1); 33 34 String data1=bfr1.readLine(); 35 System.out.println(data1); 36 37 OutputStream os=new FileOutputStream("C:\\Users\\qinghuang\\Desktop\\io2.txt"); 38 OutputStreamWriter osr=new OutputStreamWriter(os,"gbk"); 39 BufferedWriter bfw=new BufferedWriter(osr); 40 41 bfw.write(data1); 42 43 44 bfr.close(); bfr1.close(); bfw.close(); 45 isr.close(); isr1.close(); osr.close(); 46 is.close(); is1.close(); os.close(); 47 } 48 }
返回的是gbk还是utf-8或者是其他编码?你应看response返回的头文件中charset到底是什么编码然后再转换
其他几个编码方式,我都试过,打印结果都是乱码。然后我又尝试:获取字符串网页的编码方式我看了是UTF-8,当时我将myeclipse的文件系统的编码方式都改成UTF-8,代码中的转化编码也改成utf-8,结果也是乱码。然后我又按照这个思路将其他几种编码方式全部试了一遍,结果都是乱码。能具体的跟我说一下怎么改,万分感谢~
@小调~: InputStreamReader isr=new InputStreamReader(is,"gbk"); 把gbk改成utf-8就正常。我测试是这样的,不是搞java的。
URL url=new URL("http://www.baidu.com"); URLConnection urlc=url.openConnection(); InputStream is1=urlc.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(is1,"utf-8"); BufferedReader reader = new BufferedReader(inputStreamReader); String tempLine = null; StringBuffer resultBuffer = new StringBuffer(); while ((tempLine = reader.readLine()) != null) { resultBuffer.append(tempLine); } System.out.println(resultBuffer); OutputStream os=new FileOutputStream("E:\\io2.txt"); OutputStreamWriter osr=new OutputStreamWriter(os,"gb2312"); osr.write(resultBuffer.toString());
上面是测试的,所有资源没有close
@孤零落叶寒:
URL url=new URL("http://www.baidu.com"); URLConnection urlc=url.openConnection(); InputStream is1=urlc.getInputStream(); InputStreamReader isr1=new InputStreamReader(is1,"utf-8"); BufferedReader bfr1=new BufferedReader(isr1); String data1=bfr1.readLine(); StringBuffer buffer1=new StringBuffer(); buffer1.append(data1); System.out.println(buffer1); OutputStream os=new FileOutputStream("C:\\Users\\qinghuang\\Desktop\\io2.txt"); OutputStreamWriter osr=new OutputStreamWriter(os,"gb2312"); BufferedWriter bfw=new BufferedWriter(osr); bfw.write(data1);
按照你的思路我改了一下代码,试了还是不好使啊,还是乱码~,然后我把你给的代码我在我电脑上eclipse和myeclipse都试了,打印的也是乱码~好纠结啊,难受香菇。