以下代码通过FileWriter将字符串写入到TXT文件中,然后又从TXT文件中读取数据并打印出来
package jdbc;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TxtWrite {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("D:/file.txt");
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/file.txt"))){
writer.write("2024-10-01 00:00:00"); // 写入数据
writer.flush();//重要!!!
String line = bufferedReader.readLine(); // 读取数据
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileWriter在写入中文时,不能指定编码格式(JDK11之前)。以下代码使用OutputStreamWriter + FileOutputStream的方式,写入UTF-8的中文
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
public class FileWriterWithCharset {
public static void main(String[] args) {
String filePath = "D:/test.txt";
String content = "中文内容:测试编码格式 UTF-8";
// 关键:用 OutputStreamWriter 包装 FileOutputStream,指定编码
try (
// 1. 字节流:FileOutputStream(追加模式 true,与 FileWriter 一致)
FileOutputStream fos = new FileOutputStream(new File(filePath), true);
// 2. 字符流:OutputStreamWriter(指定编码为 UTF-8,也可改为 GBK)
Writer writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8)
// Writer writer = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8)); //也可以再套一层BufferedWriter做缓冲
) {
writer.write(content); // 写入中文
writer.write("\r\n"); // 换行(Windows 兼容)
writer.flush(); // 确保数据即时写入(try-with-resources 会自动关闭流)
System.out.println("写入成功,编码:UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
也可以直接使用FileOutputStream写入字符串的bytes数组(使用UTF-8编码,如果不填编码,则会使用系统默认的编码)
try(FileOutputStream out = new FileOutputStream(new File("D:/test.txt"),true)){
String line = "\n"+"这是一段中文"+"\n";
out.write(line.getBytes(StandardCharsets.UTF_8));
out.flush();
} catch (FileNotFoundException e) {
logger.error("文件未找到", e);
returnMap.put("msg", "文件未找到");
return returnMap;
} catch (IOException e) {
logger.error("文件写入时异常", e);
returnMap.put("msg", "文件写入时异常");
return returnMap;
}
---------------------------分割线------------------------------
更适合纯文本写入的场景,BufferedWriter的newLine()可支持跨平台的换行。
try(// 更适合纯文本写入的场景
BufferedWriter writer2 = new BufferedWriter(
new OutputStreamWriter(
Files.newOutputStream(
Paths.get("D:/test.txt"),StandardOpenOption.APPEND),StandardCharsets.UTF_8))){
writer2.write("这是一段中文");
writer2.newLine();
writer2.flush();
} catch (IOException e) {
e.printStackTrace();
}
NIO,写入txt文件DEMO
try (OutputStream outputStream = Files.newOutputStream(Paths.get("D:/test.txt"), StandardOpenOption.APPEND)){
outputStream.write("\n这是一段中文2\n".getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}

4757






