zoukankan      html  css  js  c++  java
  • io读取文件内容乱码处理

    这是一个最简单程序,可能跟其他场合不同;

    package com.medivh.io2;
    
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    public class InputStreamTest
    {
    	public static void main(String[] args) throws Exception
    	{
    		InputStream io = new FileInputStream("d:/test.txt");
    		
    		byte[] head = new byte[200];//设置读取范围
    		
    		 String code = "";  
    		   
             code = "gb2312";  
             
    	     if (head[0] == -1 && head[1] == -2 )  
    	     {
    	    	 code = "UTF-16";  
    	     }
    	     if (head[0] == -2 && head[1] == -1 )  
    	     {
    	    	  code = "Unicode";  
    	     }
    	     if(head[0]==-17 && head[1]==-69 && head[2] ==-65)  
    	     {
    	    	 code = "UTF-8"; 
    	     }
    	     
    	     String str ="";
    	     
    	     int length = 0;
    	     
    	     while(-1 !=(length =  io.read(head, 0, 200)))//只读取不为空的数据
    	     {
    	    	 System.out.println(length);
    	    	 
    	    	str = new String(head,0,length,code);//将读取信息用特定编码存入字符串中
    	     }
    	     
    	     System.out.println(str);
    	     
    		io.close();//关闭流
    	}
    }
    


    输出结果为:

    118
    “种族并不代表荣誉。我曾见过一些兽人,他们像最高贵的骑士那样可敬,我还见过某些人类,他们像最残忍的亡灵天灾那样邪恶。”

  • 相关阅读:
    ubuntu下安装配置apache2(含虚拟主机配置)
    ubuntu安装软件包apt-get和dpkg方法
    python日期,时间函数
    python多线程
    截取utf8中文字符串
    python解析json
    sqlite读写
    lambda,map,filter,reduce
    pyinstaller生成exe可执行程序
    对象练习
  • 原文地址:https://www.cnblogs.com/MedivhQ/p/3801438.html
Copyright © 2011-2022 走看看