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 block
e.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 block
e.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);
}
}
java读写文本文件
最新推荐文章于 2024-07-31 21:34:18 发布