java以指定编码读写文件

java以指定编码格式读写文件工具类:

package cn.geekapp.utils;

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

/**
 * 文件读写类
 */
public class FileUtil {
	/**
	 * 读取文件
	 * @param file
	 * @param charset
	 * @return
	 */
	public static String readFile(File file, String charset){
		if(file == null)
			return "";
		if(!file.exists())
			return "";
		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
			String line = "";
			while((line = reader.readLine()) != null){
				buffer.append(line);
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("readFile exception:"+e);
		}finally{
			try {
				if(reader != null)
					reader.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return buffer.toString();
	}
	
	/**
	 * 保存文件
	 * @param file
	 * @param content
	 * @param charset
	 * @return
	 */
	public static boolean saveFile(File file, String content, String charset){
		if(file == null)
			return false;
		BufferedWriter writer = null;
		boolean flag = false;
		try {
			if(!file.exists())
				file.createNewFile();
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
			writer.write(content);
			writer.flush();
			flag = true;
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("readFile exception:"+e);
		}finally{
			try {
				if(writer != null)
					writer.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return flag;
	}
}

原创内容转载请保留出处GEEK笔记(http://www.geekapp.cn/)。

原创博客,转载请标明出处:http://www.geekapp.cn/archives/272.html
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇