北在北方

太白枝头看,花开不计年,杯中浮日月,楼外是青天。

导航

写txt文件在AIX5.3系统中乱码

Posted on 2012-09-14 11:11  CN.programmer.Luxh  阅读(1054)  评论(0编辑  收藏  举报
/**
     * 写文本内容到txt文件
     * @param fileContent  文件内容
     */
    public  void writeResultFile(String fileContent) {    
        //文件存放目录
        String fileDir=ConstDefine.FILE_DIR;
        //文件名
        String fileName =new  SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".txt";
        File resultFile = new File(fileDir,fileName);
        BufferedReader bufferedReader = null; 
        BufferedWriter bufferedWriter = null; 
        try { 
             bufferedReader = new BufferedReader(new StringReader(fileContent)); 
             bufferedWriter = new BufferedWriter(new FileWriter(resultFile)); 
             char buf[] = new char[1024];         //字符缓冲区 
             int len; 
             while ((len = bufferedReader.read(buf)) != -1) { 
                 bufferedWriter.write(buf, 0, len); 
             } 
            
        } catch (IOException e) { 
            
             e.printStackTrace(); 
        } finally {
             try {
                bufferedWriter.flush();
                bufferedReader.close(); 
                bufferedWriter.close(); 
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
    }

  

  上面这个方法就是把文本内容写到txt文件中,在Window系统和Red Hat Linux 系统中都没有问题,但是在AIX5.3系统中写到txt文件后就会变成乱码。

  修改后的方法如下:(写文件的时候加上编码)

/**
     * 写文本内容到txt文件
     * @param fileContent  文件内容
     */
    public void writeResultFile(String fileContent) {
        //文件存放目录
        String fileDir=ConstDefine.FILE_DIR;
        //文件名
        String fileName =new  SimpleDateFormat("yyyyMMddHHmmsszzz").format(new Date())+".txt";
        File resultFile = new File(fileDir,fileName);
        BufferedWriter bufferedWriter = null; 
        try { 
             bufferedWriter = new BufferedWriter(new OutputStreamWriter (new FileOutputStream(resultFile),"GBK")); 
             bufferedWriter.write(fileContent,0,fileContent.length());
        } catch (IOException e) { 
             e.printStackTrace(); 
        } finally {
             try {
                bufferedWriter.flush();
                bufferedWriter.close(); 
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
    }

  

  修改后的方法在window、Linux和AIX系统中都没有发生乱码。

  如果读取文件的时候遇到乱码,也可以加上编码:

BufferedReader br = new BufferedReader(new InputStreamReader (new FileInputStream(new File(filePath)),"GBK"));