java读写文本文件

来源:互联网 发布:java 泛型方法 调用 编辑:程序博客网 时间:2024/06/05 22:39
package com.lyt.io;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import org.apache.log4j.Logger;/** * 创建文件 @ CreateTxtFile.java *  * @date 2014年2月26日 下午2:50:30 * @auther Leiyt */public class CreateTxtFile {private static String encode = "UTF-8";static Logger log=Logger.getLogger(CreateTxtFile.class);/** * 创建文件 *  * @author Leiyt * @date 2014年2月26日 下午3:00:42 * @param path *            文件路径+文件名 */public static void CreateFile(String path) {log.info("创建文件");File file = new File(path);if (!file.exists() && !file.isFile()) {try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}log.info(file.getName() + "文件已创建");} else {log.info(file.getName() + "文件已存在");}}/** * 写文件(覆盖) *  * @author Leiyt * @date 2014年2月26日 下午3:39:32 * @param path * @param content */public static void writerTxtFile(String path, String content) {log.info("写文件开始");File file = new File(path);FileWriter fw = null;try {if (file.isFile() && file.exists()) {fw = new FileWriter(file); //覆盖fw.write(content);fw.flush();fw.close();}else{System.err.println("未找到指定文件+path");}} catch (Exception e) {e.printStackTrace();}}/** * 写文件(在原文件中追加) * @author Leiyt * @date   2014年2月26日 下午4:34:37 * @param path * @param content */public static void appendTxtFile(String path, String content) {File file = new File(path);FileWriter fw = null;try {if (file.isFile() && file.exists()) {fw = new FileWriter(file,true);//追加fw.write(content);fw.flush();fw.close();}else{log.info("未找到指定文件+path");}} catch (Exception e) {e.printStackTrace();}}/** * 读取文件 *  * @author Leiyt * @date 2014年2月26日 下午3:41:05 * @param path * @return */public static String readerTxtFile(String path) {String content = "";File file = new File(path);try {if (file.isFile() && file.exists()) {BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encode));String lineTxt = "";while ((lineTxt = br.readLine()) != null) {content += lineTxt+"\n";}br.close();} else{System.err.println("未找到指定文件+path");}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return content;}/** * 设置编码格式,默认为UTF-8 *  * @author Leiyt * @date 2014年2月26日 下午3:43:39 * @param encode */public static void setEncode(String encode) {CreateTxtFile.encode = encode;}public static void main(String[] args) {log.debug("abc");CreateFile("writer.txt");String content=readerTxtFile("reader.txt");log.info(content);writerTxtFile("writer.txt", content);appendTxtFile("writer.txt", content);}}


0 0
原创粉丝点击