一、读txt文件
public static String readFile(File file, String charset){
//设置默认编码
if(charset == null){
charset = "UTF-8";
}
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charset);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
}
return sb.toString();
} catch (Exception e) {
// TODO: handle exception
}
}
return null;
}
二、写txt文件
/**
* 以FileWriter方式写入txt文件。
* @param File file:要写入的文件
* @param String content: 要写入的内容
* @param String charset:要写入内容的编码方式
*/
public static void writeToFile1(){
try {
String content = "测试使用字符串";
File file = new File("./File/test1.txt");
if(file.exists()){
FileWriter fw = new FileWriter(file,false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); fw.close();
System.out.println("test1 done!");
}
} catch (Exception e) {
// TODO: handle exception
}
}
三、文件不存在时候,主动创建文件
public static void writeToFile2(){
try {
String content = "测试使用字符串";
File file = new File("./File/test2.txt");
//文件不存在时候,主动穿件文件。
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); fw.close();
System.out.println("test2 done!");
} catch (Exception e) {
// TODO: handle exception
}
}
四、使用FileOutputStream来写入txt文件
public static void writeToFile3(){
String content = "测试使用字符串";
FileOutputStream fileOutputStream = null;
File file = new File("./File/test3.txt");
try {
if(file.exists()){
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("test3 done");
}