转自博文《Java文件编码格式转换》:

默认被转换的格式为GBK,转换成的格式为UTF-8

import info.monitorenter.cpdetector.CharsetPrinter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class EncodeFormatTransfer {

  public static String DefaultSrcEncodeFormat = "GBK";
  public static String DefaultDestEncodeFormat = "UTF-8";
  public static String UnsupportedEncodingExceptionError = "编码格式错误!";
  public static String FileNotFoundExceptionError = "文件不存在!";
  public static String IOExceptionError = "文件读写错误!";
  public static String IsUtf8File = "文件是UTF-8编码格式!";
  public static String IsNotUtf8File = "文件不是UTF-8编码格式!";
  public static String readFile(String path,String encodeFormat){
  if((encodeFormat==null || encodeFormat.equals(""))){
  if(isUTF8File(path))
    encodeFormat = DefaultDestEncodeFormat;
  else 
    encodeFormat = DefaultSrcEncodeFormat;
  }
  try {
    String context = "";
    InputStreamReader isr;
    isr = new InputStreamReader(new FileInputStream(path),encodeFormat);
    BufferedReader br=new BufferedReader(isr);
    String line;
    while((line=br.readLine())!=null){
      context += line + "\r\n";
      System.out.println(line);
  }
  br.close();
  return context;
  } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    System.out.println(UnsupportedEncodingExceptionError);
    e.printStackTrace();
  } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    System.out.println(FileNotFoundExceptionError);
    e.printStackTrace();
  }catch (IOException e) {
    // TODO Auto-generated catch block
    System.out.println(IOExceptionError);
    e.printStackTrace();
  };
  return "";   
}

/*public static boolean isUTF8File(String path){
  try {
    File file = new File(path);
    CharsetPrinter detector = new CharsetPrinter();   
    String charset = detector.guessEncoding(file);
    InputStream in = new java.io.FileInputStream(file);
    byte[] b = new byte[3];
    in.read(b);
    in.close();
    System.out.println(b[0] + " " + b[1] + " " + b[2]);
    if (b[0] == 0xEF && b[1] == 0xBB && b[2] == 0XBF){
      System.out.println(IsUtf8File);
          return true;
        }
          if (b[0] == -17 && b[1] == -69 && b[2] == -65){
          System.out.println(IsUtf8File);
          return true;
        }
  } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println(FileNotFoundExceptionError);
  }catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println(IOExceptionError);
  }
  System.out.println(IsNotUtf8File);
  return false;   
}*/
public static boolean isUTF8File(String path){
  try {
     File file = new File(path);
    CharsetPrinter detector = new CharsetPrinter();   
    String charset = detector.guessEncoding(file);
    if(charset.equalsIgnoreCase(DefaultDestEncodeFormat)){
      System.out.println(IsUtf8File);
      return true;
    }
  } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println(FileNotFoundExceptionError);
  }catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println(IOExceptionError);
  }
  System.out.println(IsNotUtf8File);
  return false;   
}

public static String transfer(String context,String encodeFormat) {
  if(encodeFormat==null || encodeFormat.equals(""))
    encodeFormat = DefaultDestEncodeFormat;
  try {
    byte[] content = context.getBytes();
    String result = new String(content,encodeFormat);
    return result;
  } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    System.out.println(UnsupportedEncodingExceptionError);
    e.printStackTrace();
  }
  return "";
}

public static void writeFile(String context,String path,String destEncode){
  File file = new File(path);
  if(file.exists())
    file.delete();
  BufferedWriter  writer;
  try {
    FileOutputStream fos = new FileOutputStream(path,true);    
    writer = new BufferedWriter(new OutputStreamWriter(fos, destEncode));
    writer.append(context);
    writer.close();
  } catch (IOException e) {
    System.out.println(IOExceptionError);
    e.printStackTrace();
  }
}

public static void writeFile(String context,String path){
  File file = new File(path);
  if(file.exists())
  file.delete();
  Writer  writer;
  try {
    writer = new FileWriter(file, true);
    writer.append(context);
    writer.close();
  } catch (IOException e) {
    System.out.println(IOExceptionError);
    e.printStackTrace();
  }
}

public static void transfer(String srcPath,String destPath,String srcEncode,String destEncode){
  if(destPath==null || destPath.equals(""))
    destPath = srcPath;
  String context = readFile(srcPath,srcEncode);
  context = transfer(context,destEncode);
  writeFile(context,destPath,destEncode);
}

public static void transfer(String srcPath,String destPath,String destEncode){
  if(isUTF8File(srcPath)){
    transfer(srcPath,destPath,DefaultDestEncodeFormat,destEncode);
  }else{
    transfer(srcPath,destPath,DefaultSrcEncodeFormat,destEncode);
  }
}

public static void main(String args[]){
  String path1 = "f:/Notepad1.java";
  String path2 = "f:/Notepad2.java";
  transfer(path1,path2,"UTF-8");
  transfer(path1,path2,"UTF-8","UTF-8");
}
}

 
java读取文件,处理过程中,可能因为文件的编码问题导致了中文乱码。有时需要将UTF-8的改为ANSI的编码。以下代码就可以判断文件是什么编码方式。
主要jar包:cpdetector.jar 

下载地址: http://cpdetector.sourceforge.net/

同时还需jchardet-1.0.jar这个包,否则detector.add(cpdetector.io.JChardetFacade.getInstance());  会报错;

下载地址: http://www.jarfinder.com/index.php/jars/versionInfo/40297

还有一个antlr.jar,不然运行过程中detector.add(new ParsingDetector(false));会报错;

下载地址: http://www.java2s.com/Code/Jar/ABC/Downloadantlrjar.htm

 
 

Java文件编码格式转换的更多相关文章

  1. FilesCodingConvert--批量文件编码格式转换工具

    FilesCodingConvert–批量文件编码格式转换工具 简介 最近开始学习使用Android Studio,因为它的方便易用,我打算以后就不在使用ADT的方式编写Android项目了.当从Ec ...

  2. java项目编码格式转换(如GBK转UTF-8)

    昨天突然下了个Java项目,把项目导入到eclipse中,发现项目是gbk编码格式想把项目变为utf-8,但是发现转换格式比较麻烦就写了这个代码,后面改进了下,想到说不定有人也需要就把它写了出来 代码 ...

  3. Linux 文件编码格式转换

    如果需要在Linux 中操作windows下的文件,那么经常遇到文件编码转换的问题. Windows中默认的文件格式是GBK(gb2312),而Linux一般都是UTF-. 查看文件编码 在vim 中 ...

  4. Linux下查看文件编码,文件编码格式转换和文件名编码转换

    linux相关   2008-10-07 10:46   阅读1392   评论0   字号: 大大  中中  小小  如果你需要在Linux中 操作windows下的文件,那么你可能会经常遇到文件编 ...

  5. MacOS 自带文件编码格式转换工具

    [命令功能]iconv 是Linux操作系统用于将文本编码格式从一种转外另外一种的工具命令.[使用方法] iconv [OPTION...] [-f ENCODING] [-t ENCODING] [ ...

  6. ubuntu 文件编码格式 转换

    正在学习jquery,之前在windows下弄的编码到了 ubuntu下,乱码: 找到一个方法: iconv : 源文件:a.htm 格式:gbk: 目标:    a.html 格式:utf8: ic ...

  7. 在Vim中查看文件编码和文件编码转换

    在Vim中查看文件编码和文件编码转换 风亡小窝 关注  0.2 2016.09.26 22:43* 字数 244 阅读 5663评论 0喜欢 2 在Vim中查看文件编码 :set fileencodi ...

  8. 解决eclipse中的Java文件,使用idea打开的乱码问题

    吐槽: 在克隆一些Github上面资源的时候,使用idea打开,会出现乱码的情况 而使用eclipse打开,这种情况就会消失.「是因为eclipse使用的是GBK编码,idea使用的是utf-8」 这 ...

  9. Linux查看文件编码格式及文件编码转换

    Linux查看文件编码格式及文件编码转换   如果你需要在Linux 中操作windows下的文件,那么你可能会经常遇到文件编码转换的问题.Windows中默认的文件格式是GBK(gb2312),而L ...

随机推荐

  1. 基于Microchip单片机的触摸感应技术

    Microchip提供两种电容式触摸感应解决方案,一种为张驰振荡器方式,即通过检测触摸感应电容充放电的频率变化,来检测是否有键按下,根据单片机集成的硬件资源不同,另一种通过Microchip单片机集成 ...

  2. ABAP 内表 详解

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  3. .net中类型转换的案例

    .net中三种数据类型转换区别((int),Int32.Parse() 和 Convert.toInt32() )(typename)valuename,是通用方法: Convert类提供了灵活的类型 ...

  4. Scrum Meeting---One(2015-10-20)

    一.scrum meeting 在上周六我们团队进行了一次会议,讨论了我们团队的项目以及项目分工.首先是确立我们的项目,在团队的激烈讨论下我们决定做一个校园相关的APP.然后对于这个项目我们大致进行了 ...

  5. HIHO 线段树(单点)

    #include <stdio.h> #include <string.h> #include <math.h> #include <iostream> ...

  6. [转载] Google数据中心网络技术漫谈

    原文: http://www.sdnlab.com/12700.html?from=timeline&isappinstalled=0#10006-weixin-1-52626-6b3bffd ...

  7. 2014 Multi-University Training Contest 1

    A hdu4861 打表找规律 #include <iostream> #include<cstdio> #include<cstring> #include< ...

  8. Oracle 10g实现存储过程异步调用

    DBMS_JOB是什么?DBMS_JOB是Oracle数据库提供的专家程序包的一个.主要用来在后台运行程序,是数据库中一个极好的工具. 可用于自动调整调度例程任务,例如分析数据表,执行一些归档操作,清 ...

  9. Linux下的字符集问题

    怎么设置Linux系统中文语言,这是很多小伙伴在开始使用Linux的时候,都会遇到一个问题,就是终端输入命令回显的时候中文显示乱码.出现这个情况一般是由于没有安装中文语言包,或者设置的默认语言有问题导 ...

  10. hdu 4864 Task

    题目链接:hdu 4864 其实就是个贪心,只是当初我想的有偏差,贪心的思路不对,应该是这样子的: 因为 xi 的权值更重,所以优先按照 x 来排序,而这样的排序方式决定了在满足任务(即 xi > ...