首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java设立读取和写入文本的编码格式

2012-12-18 
java设置读取和写入文本的编码格式在某些情况之下,我们需要对文本的读取和写入设定编码格式,否则会出现读

java设置读取和写入文本的编码格式

在某些情况之下,我们需要对文本的读取和写入设定编码格式,否则会出现读取和写入文本出现乱码的情况,通过以下方式可以解决编码设置的问题。


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test {
??? private static InputStream is = null ;
??? private static FileOutputStream fos = null ;
??? private static OutputStreamWriter writer = null;
??? private static String charEncoding = "UTF-8";
???
??? //读取文本
??? public static InputStream getInputStream(String path) throws IOException{
??? ??? String line =null;
??? ??? try {
??? ??? ??? is = new FileInputStream(path) ;
??? ??? ??? BufferedReader reader = new BufferedReader(new InputStreamReader(is,charEncoding)) ;
??? ??? ??? while((line = reader.readLine())!=null){
??? ??? ??? ??? System.out.println(line);
??? ??? ??? }
??? ??? ??? is.close();
??? ??? } catch (FileNotFoundException e) {
??? ??? ??? e.printStackTrace();
??? ??? }
??? ??? return null ;
??? }

??? //写入文本
??? public static void Writer(String path , String charEncoding , String content){??? ???
??? ??? try {
??? ??? ??? fos = new FileOutputStream(new File(path)) ;??? ??? ???
??? ??? ??? writer = new OutputStreamWriter(fos,charEncoding);
??? ??? ??? writer.write(content);
??? ??? ??? writer.close();
??? ??? ??? fos.close() ;
??? ??? } catch (FileNotFoundException e) {
??? ??? ??? e.printStackTrace();
??? ??? } catch (IOException e) {
??? ??? ??? e.printStackTrace();
??? ??? }
??? }

}

?

?

1 楼 Mars.CN 2012-05-18   这个好像没什么用吧?读只能读UTF-8格式的,写也是,没有意义呀 2 楼 mfan 2012-05-21   Mars.CN 写道这个好像没什么用吧?读只能读UTF-8格式的,写也是,没有意义呀
也不是这么说,只是你还没遇到中文文本处理的问题。

热点排行