版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
文件读取与写入的demo,将其封装成一个函数,直接传入需要读取的文件路径,写入只要执行文件和写入内容即可。
import java.io.*;
public class FileTest {
public static void main(String[] args) {
//获得当前项目的路径
String path = System.getProperty("user.dir");
String result = readFile(path + "/1.txt");
System.out.println(result);
writeFile(path + "/2.txt", "写入1\n2\n3\n");
}
/**
* 读取文件
*/
public static String readFile(String pathname) {
StringBuffer str = new StringBuffer();
//防止文件建立或读取失败,用catch捕捉错误并打印
try (FileReader reader = new FileReader(pathname);
BufferedReader br = new BufferedReader(reader)
) {
String line;//逐行读取
while ((line = br.readLine()) != null) {
str.append(line);
str.append("\r\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
/**
* 写入文件,如果文件存在,追加写入
*/
public static void writeFile(String pathname, String content) {
try {
File writeName = new File(pathname);
try (FileWriter writer = new FileWriter(writeName, true);
BufferedWriter out = new BufferedWriter(writer)
) {
out.write(content);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}