Home >Java >JavaBase >Java writes files that are garbled

Java writes files that are garbled

angryTom
angryTomOriginal
2019-11-20 17:03:043006browse

Java writes files that are garbled

Java writing files is garbled

When we read and write file streams, we often encounter Of course, the cause of garbled codes cannot be the same. Here we mainly introduce the problem of garbled codes caused by the file encoding format. First, let’s clarify the concepts and differences between text files and binary files.

Text files are files based on character encoding. Common encodings include ASCII encoding, UNICODE encoding, ANSI encoding, etc. Binary files are files based on value encoding. You can specify what a certain value means according to the specific application (such a process can be regarded as custom encoding.)

So it can be seen that text files are basically It is fixed-length encoding (there are also non-fixed-length encodings such as UTF-8). Binary files can be regarded as variable-length encoding, because it is value encoding. How many bits represent a value is entirely up to you.

The specific operations are as follows:

Write the file in the format specified by the file

/**
   * 按照指定的路径和编码格式保存文件内容,这个方法因为用到了字符串作为载体,为了正确写入文件(不乱码),只能写入文本内容,安全方法
   * 
   * @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;
  }

php Chinese website, a large number of free Java introductory tutorials, welcome online study!

The above is the detailed content of Java writes files that are garbled. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn