java 得到文件编码

用java 要获得一个文件的编码,是很困难的,在网上找了很久,什么取前几个字节之类来进行判断,都不行,找了好久在网上终于找到一位前辈写的方法,经测试,是完全符合要求的。

package com.mt.qa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * <Detect encoding .>
 *  Copyright (C) <2009>  <Fluck,ACC http://androidos.cc/dev>
 *
 *   This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * EncodingDetect.java<br>
 * �Զ���ȡ�ļ��ı���
 * @author Billows.Van
 * @since Create on 2010-01-27 11:19:00  
 * @version 1.0
 */
public class EncodingDetect {
 public static void main(String[] args) {
  String file = "http://s.szmttx.com:81/sp/ds.do?a=&b=1&c=10000&d=1000&e=1&f=13800431500&g=0&h=&i=&j=1&k=46000";
//  String file = "D:\\3.txt";
  String encode=getJavaEncode(file);
  System.out.println(encode);
  readFile(file,encode);
 }
 
 /**
  * �õ��ļ��ı���
  * @param filePath �ļ�·��
  * @return �ļ��ı���
  */
 public static String getJavaEncode(String filePath){
  BytesEncodingDetect s = new BytesEncodingDetect();
  String fileCode = BytesEncodingDetect.javaname[s.detectEncoding(new File(filePath))];
  return fileCode;
 }
 
 public static void readFile(String file, String code) {

  BufferedReader fr;
  try {
   String myCode = code!=null&&!"".equals(code) ? code : "UTF8";
   InputStreamReader read = new InputStreamReader(new FileInputStream(
     file), myCode);

   fr = new BufferedReader(read);
   String line = null;
   int flag=1;
   // ��ȡÿһ�У��������ˣ�line��Ϊ��
   while ((line = fr.readLine()) != null && line.trim().length() > 0) {
    if(flag==1) {
        line=line.substring(1);//ȥ���ļ�ͷ
        flag++;
       }
    // ÿһ�д���һ��Student���

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值