ITeye博客

Java指定编码读写文件(UTF-8)

Fangrn · 2010-11-30 14:00 · j2ee · 编程语言 · Markdown

有时我们需要程序动态生成jsp文件,采取系统默认的编码操作的文件出来的结果往往不是我们想要的,原因是中文显示总是是乱码。

 

 

读取

     import  java.io.BufferedReader; 
     import  java.io.FileInputStream; 
     import  java.io.InputStreamReader; 

    String FileContent  =   "" ;  //  文件很长的话建议使用StringBuffer
     try  {
        FileInputStream fis  =   new  FileInputStream( " d:\\input.txt " );
        InputStreamReader isr  =   new  InputStreamReader(fis,  " UTF-8 " );
        BufferedReader br  =   new  BufferedReader(isr);
        String line  =   null ;
         while  ((line  =  br.readLine())  !=   null ) {
            FileContent  +=  line;
            FileContent  +=   "\r\n " ;  //  补上换行符
        }
    }  catch  (Exception e) {
        e.printStackTrace();
    }

 

写入

     import  java.io.FileOutputStream;
     import  java.io.OutputStreamWriter;

    String FileContent  =   " 文件内容 " ;
     try  {
        FileOutputStream fos  =   new  FileOutputStream( " d:\\output.txt " );
        OutputStreamWriter osw  =   new  OutputStreamWriter(fos,  " UTF-8 " );
        osw.write(FileContent);
        osw.flush();
    }  catch  (Exception e) {
        e.printStackTrace();
    }

       读写文件是最常用的操作之一,每次将相应的代码片段复制过来不仅麻烦,还会影响整体的美观。为此我单独写了一个文件操作的类,需要时先把这个类的代码粘过去,再调用就方便多了。 

import  java.io.BufferedReader;
import  java.io.FileInputStream;
import  java.io.FileOutputStream;
import  java.io.InputStreamReader;
import  java.io.OutputStreamWriter;

public   class  FileManager {
     public   static  String read(String fileName, String encoding) {
        StringBuffer fileContent  =   new  StringBuffer();
         try  {
            FileInputStream fis  =   new  FileInputStream(fileName);
            InputStreamReader isr  =   new  InputStreamReader(fis, encoding);
            BufferedReader br  =   new  BufferedReader(isr);
            String line  =   null ;
             while  ((line  =  br.readLine())  !=   null ) {
                fileContent.append(line);
                fileContent.append(System.getProperty( " line.separator " ));
            }
        }  catch  (Exception e) {
            e.printStackTrace();
        }
         return  fileContent.toString();
    }

     public   static   void  write(String fileContent, String fileName, String encoding) {
         try  {
            FileOutputStream fos  =   new  FileOutputStream(fileName);
            OutputStreamWriter osw  =   new  OutputStreamWriter(fos, encoding);
            osw.write(fileContent);
            osw.flush();
        }  catch  (Exception e) {
            e.printStackTrace();
        }
    }
}

 

调用示例:

写入 FileManager.write("Hello, World!", "D:\\test.txt", "UTF-8");

读取 System.out.println(FileManager.read("D:\\test.txt", "UTF-8"));

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。