一个常用的读取和写入txt的工具类
package util;
import java.io.*;
/**
* @author
* wxg
*/
public class TxtUtil {
/**
* 读取txt文件
* @param path
* 文件路径
* @return
*/
public StringBuilder readTxt(String path){
return readTxt2(path,"gbk");
}
/**
* 读取txt文件
* @param path
* 文件路径
* @param encoding
* 文件编码
* @return
*/
public StringBuilder readTxt(String path,String encoding){
return readTxt2(path,encoding);
}
private StringBuilder readTxt1(String path){
File file = new File(path);
if (!file.exists()) {
return null;
}
try {
Reader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String str;
while ((str = br.readLine())!=null){
sb.append(str).append("
");
}
reader.close();
br.close();
return sb;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder readTxt2(String path,String encoding){
File file = new File(path);
if (!file.exists()) {
return null;
}
try {
InputStream is = new FileInputStream(path);
InputStreamReader isr = new InputStreamReader(is,encoding);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String str;
while ((str = br.readLine())!=null){
sb.append(str).append("
");
}
br.close();
isr.close();
is.close();
return sb;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void writeTxt(String text,String path){
writeTxt(text,path,false,"gbk");
}
public void writeTxt(String text,String path,boolean append){
writeTxt(text,path,append,"gbk");
}
public void writeTxt(String text,String path,boolean append, String encoding) {
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
OutputStream os = new FileOutputStream(path, append);
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(text);
bw.newLine();
bw.close();
osw.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}