欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java读取、写入文件如何解决乱码问题

程序员文章站 2024-03-05 12:37:30
读取文件流时,经常会遇到乱码的现象,造成乱码的原因当然不可能是一个,这里主要介绍因为文件编码格式而导致的乱码的问题。首先,明确一点,文本文件与二进制文件的概念与差异。 文...

读取文件流时,经常会遇到乱码的现象,造成乱码的原因当然不可能是一个,这里主要介绍因为文件编码格式而导致的乱码的问题。首先,明确一点,文本文件与二进制文件的概念与差异。

文本文件是基于字符编码的文件,常见的编码有ascii编码,unicode编码、ansi编码等等。二进制文件是基于值编码的文件,你可以根据具体应用,指定某个值是什么意思(这样一个过程,可以看作是自定义编码。)

因此可以看出文本文件基本上是定长编码的(也有非定长的编码如utf-8)。而二进制文件可看成是变长编码的,因为是值编码嘛,多少个比特代表一个值,完全由你决定。

 对于二进制文件,是千万不能使用字符串的,因为字符串默认初始化时会使用系统默认编码,然而,二进制文件因为自定义编码自然与固定格式的编码会有所冲突,所以对于二进制的文件只能采用字节流读取、操作、写入。

  对于文本文件,因为编码固定,所以只要在读取文件之前,采用文件自身的编码格式解析文件,然后获取字节,再然后,通过指定格式初始化字符串,那么得到的文本是不会乱码的。虽然,二进制文件也可以获取到它的文本编码格式,但是那是不准确的,所以不能同日而语。

具体操作如下:

1)获取文本文件的格式

public static string getfileencode(string path) {
    string charset ="asci";
    byte[] first3bytes = new byte[3];
    bufferedinputstream bis = null;
    try {
      boolean checked = false;
      bis = new bufferedinputstream(new fileinputstream(path));
      bis.mark(0);
      int read = bis.read(first3bytes, 0, 3);
      if (read == -1)
        return charset;
      if (first3bytes[0] == (byte) 0xff && first3bytes[1] == (byte) 0xfe) {
        charset = "unicode";//utf-16le
        checked = true;
      } else if (first3bytes[0] == (byte) 0xfe && first3bytes[1] == (byte) 0xff) {
        charset = "unicode";//utf-16be
        checked = true;
      } else if (first3bytes[0] == (byte) 0xef && first3bytes[1] == (byte) 0xbb && first3bytes[2] == (byte) 0xbf) {
        charset = "utf8";
        checked = true;
      }
      bis.reset();
      if (!checked) {
        int len = 0;
        int loc = 0;
        while ((read = bis.read()) != -1) {
          loc++;
          if (read >= 0xf0)
            break;
          if (0x80 <= read && read <= 0xbf) //单独出现bf以下的,也算是gbk
            break;
          if (0xc0 <= read && read <= 0xdf) {
            read = bis.read();
            if (0x80 <= read && read <= 0xbf) 
            //双字节 (0xc0 - 0xdf) (0x80 - 0xbf),也可能在gb编码内
              continue;
            else
              break;
          } else if (0xe0 <= read && read <= 0xef) { //也有可能出错,但是几率较小
            read = bis.read();
            if (0x80 <= read && read <= 0xbf) {
              read = bis.read();
              if (0x80 <= read && read <= 0xbf) {
                charset = "utf-8";
                break;
              } else
                break;
            } else
              break;
          }
        }
        //textlogger.getlogger().info(loc + " " + integer.tohexstring(read));
      }
    } catch (exception e) {
      e.printstacktrace();
    } finally {
      if (bis != null) {
        try {
          bis.close();
        } catch (ioexception ex) {
        }
      }
    }
    return charset;
  }
 
  private static string getencode(int flag1, int flag2, int flag3) {
    string encode="";
    // txt文件的开头会多出几个字节,分别是ff、fe(unicode),
    // fe、ff(unicode big endian),ef、bb、bf(utf-8)
    if (flag1 == 255 && flag2 == 254) {
      encode="unicode";
    }
    else if (flag1 == 254 && flag2 == 255) {
      encode="utf-16";
    }
    else if (flag1 == 239 && flag2 == 187 && flag3 == 191) {
      encode="utf8";
    }
    else {
      encode="asci";// ascii码
    }
    return encode;
  }

2)通过文件的编码格式读取文件流

/**
   * 通过路径获取文件的内容,这个方法因为用到了字符串作为载体,为了正确读取文件(不乱码),只能读取文本文件,安全方法!
   */
  public static string readfile(string path){
    string data = null;
    // 判断文件是否存在
    file file = new file(path);
    if(!file.exists()){
      return data;
    }
    // 获取文件编码格式
    string code = fileencode.getfileencode(path);
    inputstreamreader isr = null;
    try{
      // 根据编码格式解析文件
      if("asci".equals(code)){
        // 这里采用gbk编码,而不用环境编码格式,因为环境默认编码不等于操作系统编码 
        // code = system.getproperty("file.encoding");
        code = "gbk";
      }
      isr = new inputstreamreader(new fileinputstream(file),code);
      // 读取文件内容
      int length = -1 ;
      char[] buffer = new char[1024];
      stringbuffer sb = new stringbuffer();
      while((length = isr.read(buffer, 0, 1024) ) != -1){
        sb.append(buffer,0,length);
      }
      data = new string(sb);
    }catch(exception e){
      e.printstacktrace();
      log.info("getfile io exception:"+e.getmessage());
    }finally{
      try {
        if(isr != null){
          isr.close();
        }
      } catch (ioexception e) {
        e.printstacktrace();
        log.info("getfile io exception:"+e.getmessage());
      }
    }
    return data;
  }

3)通过文件指定的格式写入文件

/**
   * 按照指定的路径和编码格式保存文件内容,这个方法因为用到了字符串作为载体,为了正确写入文件(不乱码),只能写入文本内容,安全方法
   * 
   * @param data
   *     将要写入到文件中的字节数据
   * @param path
   *     文件路径,包含文件名
   * @return boolean 
   *      当写入完毕时返回true;
   */
  public static boolean writefile(byte data[], string path , string code){
    boolean flag = true;
    outputstreamwriter osw = null;
    try{
      file file = new file(path);
      if(!file.exists()){
        file = new file(file.getparent());
        if(!file.exists()){
          file.mkdirs();
        }
      }
      if("asci".equals(code)){
        code = "gbk";
      }
      osw = new outputstreamwriter(new fileoutputstream(path),code);
      osw.write(new string(data,code));
      osw.flush();
    }catch(exception e){
      e.printstacktrace();
      log.info("tofile io exception:"+e.getmessage());
      flag = false;
    }finally{
      try{
        if(osw != null){
          osw.close();
        }
      }catch(ioexception e){
        e.printstacktrace();
        log.info("tofile io exception:"+e.getmessage());
        flag = false;
      }
    }
    return flag;
  }

4)对于二进制文件而且内容很少的,例如word文档等,可以使用如下方式读取、写入文件

/**
   * 从指定路径读取文件到字节数组中,对于一些非文本格式的内容可以选用这个方法
   *      457364578634785634534
   * @param path
   *     文件路径,包含文件名
   * @return byte[]
   *       文件字节数组
   *      
   */
  public static byte[] getfile(string path) throws ioexception {
    fileinputstream stream=new fileinputstream(path);
    int size=stream.available();
    byte data[]=new byte[size];
    stream.read(data);
    stream.close();
    stream=null;
    return data;
  }
 
 
 
  /**
   * 把字节内容写入到对应的文件,对于一些非文本的文件可以采用这个方法。
   * @param data
   *      将要写入到文件中的字节数据
   * @param path
   *      文件路径,包含文件名
   * @return boolean isok 当写入完毕时返回true;
   * @throws exception
   */
  public static boolean tofile(byte data[], string path) throws exception {
    fileoutputstream out=new fileoutputstream(path);
    out.write(data);
    out.flush();
    out.close();
    out=null;
    return true;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助。