java 读写UTF-8文件的方法


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.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

  

java 读写UTF-8文件的方法:

	private void writeUtf8File(String fileName, char[] fileContent) {
		// java中文件操作体现了设计模式中的装饰者模式 。
		// 以UTF-8编码写入文件:
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		try {
			fos = new FileOutputStream(fileName);
			osw = new OutputStreamWriter(fos, "UTF-8");
			osw.write(fileContent);
			osw.flush();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				osw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private void readUtf8File(String fileName) {
		// 以utf-8编码读取文件:
		FileInputStream fis = null;
		InputStreamReader isr = null;
		String fileContent = "";

		try {
			fis = new FileInputStream(fileName);
			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 (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

 

调用例子:

 

上一篇:python第一课


下一篇:Java反射机制