最近在做一个FileUtil,技术采用New IO, 在做的时候出现了编码问题! 
例如: 
我采用writeFile("D:\test.txt","中国",null) 
然后我用readFile("D:\test.txt")读结果就会返回乱码! 
后来我用Charset解码 , 获取目标文件编码(System.getProperty("file.encoding")),但是还是不行. 
估计我应该要获得目标文件字节流的编码,这样才能根据相应的编码去读文件. 
我怎么样才能判断目标文件的字节流编码呢? 
或许我们会有更好的办法.请各位指教?谢谢! 
    // 读文件采用的字符编码.   
    private static Charset charset = Charset.forName(System.getProperty("file.encoding"));   
    /**  
     * 读文件  
     * @param fileName  
     * @return 读入的字符串  
     */    
    public String readFile(String fileName){   
        CharBuffer cb = null;   
        try {   
            FileChannel in = new FileInputStream(fileName).getChannel();   
            int size = (int)in.size();   
            MappedByteBuffer mppedByteBuffer = in.map(FileChannel.MapMode.READ_ONLY, 0, size);   
            cb = charset.newDecoder().decode(mppedByteBuffer);   
            in.close();   
        } catch(FileNotFoundException e) {   
            e.printStackTrace();   
        } catch(IOException e){   
            e.printStackTrace();   
        }    
        return cb.toString();   
    }   
  
/**  
     * 创建文件(写文件)  
     * @param fileName  文件名  
     * @param content   内容  
     * @param encoding  编码 (就是你需要以哪一种编码格式进行写入) . 默认采用(utf-8).  
     * @return true 创建成功 ,false 创建失败  
     */  
    public boolean writeFile(String fileName,String content,String encoding){   
        try{   
            FileChannel out = new FileOutputStream(fileName).getChannel();   
            encoding = encoding == null ? "" : encoding;   
            if(encoding.length() <= 0)   
                encoding = "utf-8";   
            out.write(ByteBuffer.wrap(content.getBytes(encoding)));   
            out.close();   
            return true;   
            }catch(FileNotFoundException e){   
                e.printStackTrace();   
            }catch(IOException e){   
                e.printStackTrace();   
            }   
        return false;   
    }  

解决方案 »

  1.   

    你先getEncoding()一下看看文件的编码方式,然后再进行转码..
      

  2.   

    private static Charset charset = Charset.forName(System.getProperty("file.encoding"));  
    这里已经获得了文件的编码格式.
    但是,读出来的还是乱码.为什么?
    我做了这样测试
    1,我先用writeFile()写,编码用utf-8
    然后将charset改成了 
    charset = Charset.forName(System.getProperty("utf-8"));
    再用readFile()读 ,结果完全正确.2, 我用writeFile()写,编码用GBK
    charset不变用utf-8
    结果很明显,出现异常.3, 我用writeFile()写,编码用GBK
    charset 改成 charset = Charset.forName(System.getProperty("file.encoding"));  
    根据文件编码改结果正确,
    但是writeFile()写,编码用utf-8
    读出来结果开始出现乱了,郁闷  ?????