Java对txt文件读取与写入操作
直接上代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
public class ReadTxt {
/**传入txt路径读取txt文件
* @param txtPath
* @return 返回读取到的内容
*/
public static String readTxt(String txtPath) {
File file = new File(txtPath);
if(file.isFile() && file.exists()){
try {
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer sb = new StringBuffer();
String text = null;
while((text = bufferedReader.readLine()) != null){
sb.append(text);
sb.append("\n"); //换行
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**使用FileOutputStream来写入txt文件
* @param txtPath txt文件路径
* @param content 需要写入的文本
*/
public static void writeTxt(String txtPath,String content){
FileOutputStream fileOutputStream = null;
File file = new File(txtPath);
try {
if(!file.exists()){
//判断文件是否存在,如果不存在就新建一个txt
System.out.println("原来没有这个文件,现在创建一个···");
file.createNewFile();
} else {
System.out.println("原来有这个文件,直接写入");
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 主函数,用来测试读写函数
public static void main(String[] args){
/**
* 调用读文件函数readTxt并输出
*/
writeTxt("D:/myh/result.txt", "测试写入txt文件内容");
String str = readTxt("D:/myh/result.txt");
System.out.println(str);
}
}
注意:createNewFile()函数
返回值为boolean类型,用来判断文件是否创建成功
用法:boolean b = file.createNewFile();
如果原来没有指定的文件,则创建一个指定路径的文件,此时文件创建成功,则b的值为true;
如果有指定的文件,那么文件创建失败,此时返回值为false。