---
title: "java设置读取和写入文本的编码格式"
author: "mfan"
date: "2011-04-25T01:04:31Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-04-25T01:04:31Z"
id: 1014549
url: "https://mfan.iteye.com/blog/1014549"
---

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

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();  
        }  
    }

}