JAVA的IO流读取数据时,解决中文乱码,还有个别中文乱码问题

情况:用IO流读取数据时,若是不设置编码格式,出来的数据未必是我们所要的

解决:读取数据时,设置编码

代码:(字符串设置对应的编码即可,但这种方式,会导致个别中文乱码,貌似是byte[]导致的

		
    //这里我通过socket方式,获取流,并读取数据
    //代理需要外置配置(代理配置需要判断,若有配置,则添加,若无配置,则不添加)
    Socket socket = new Socket("192.168.99.100", 80);
	String url = "GET " + href + " HTTP/1.1\r\n\r\n";
	socket.getOutputStream().write(new String(url).getBytes());  
    InputStream is = socket.getInputStream();
    byte[] bs = new byte[1024]; 
	int i;
	StringBuilder str = new StringBuilder();
	while ((i = is.read(bs)) > 0) {
		//一定要加编码,不然,在输出到文件时,部分数据会乱
		str.append(new String(bs, 0, i,"UTF-8"));
        //由于socket读取不会断开,所以只能自断开连接读取
		if(new String(bs, 0, i,"UTF-8").contains("")){
		   break;
		}
	}

 

解决个别中文乱码问题:

代码:

//代理需要外置配置(代理配置需要判断,若有配置,则添加,若无配置,则不添加)
		Socket socket = new Socket("192.168.99.100", 80);
		//Socket socket = new Socket();
		String url = "GET " + href + " HTTP/1.1\r\n\r\n";
		socket.getOutputStream().write(new String(url).getBytes());
		InputStream is = socket.getInputStream();
		
		//解决个别中文乱码
		StringBuilder str = new StringBuilder("");
		InputStreamReader isr = new InputStreamReader(is,"UTF-8");
		BufferedReader br = new BufferedReader(isr);
		String line = null;  
		while ((line = br.readLine()) != null) {
			 str.append(line + "\n");
		     if(line.contains("")){
		    	 break;
		     }
		}

 

文章参考:

读取数据个别几个中文字符乱码问题

你可能感兴趣的:(JAVA)