java - 如何使用 Spring Boot 保存在 .txt 文件中?
问题描述
我需要创建一个 REST api,将名称保存在 .txt 文件中,并且我可以在需要时检索它们。下面我有代码。我正在使用弹簧启动框架。
我的 REST 控制器:
@RequestMapping(value = "/people", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<String> escreverArquivo() throws Exception {
String line = "";
try {
File file = new File("nomes.txt");
// Se o arquivo nao existir, ele gera
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
// Escreve e fecha arquivo
bw.write(line);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<String>(line, HttpStatus.CREATED);
}
@RequestMapping(value = "/pessoas", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> lerArquivo() throws Exception {
String line = null;
try {
FileReader ler = new FileReader("nomes.txt");
BufferedReader reader = new BufferedReader(ler);
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<String>(line, HttpStatus.OK);
}
第一种方法不会添加任何不在字符串行内的内容,第二种方法不会在屏幕上显示任何内容,仅在 sts 控制台中显示。
解决方案
您不应该使用文本文件来存储要保留任何时间的任何数据。它们不是一种可靠的数据存储方式,尤其是当您的 api 负载增加时。
您在评论中提到您的测试需要一个文本文件,但您应该考虑这是否是一个好主意。您的测试应该测试代码的行为,而不是实现。saveName()
测试应该对任何使和getNames()
(或等效功能)按预期运行的代码感到满意。
在尝试使用诸如 Spring Boot 之类的东西之前,首先熟悉 Java 的基础知识是非常值得的。
但是,如果您真的很想将字符串保存到文本文件中,Apache Commons IO 库提供了几个很好的帮助方法,最值得注意的是:
FileUtils.write(new File("myFile.txt"), "Content Text", "UTF-8");
但是,我强烈建议您考虑是否真的需要未加密、非冗余、容易损坏且可能未备份的文本文件来存储重要数据。
推荐阅读
- python - 如何修复 AttributeError:“StringVar”对象没有属性“_name”
- c++ - 在 C++ 中读取二进制文件会返回意外值
- python - 习惯函数 Python 3.7
- javascript - 您如何将光标聚焦在位于 Bootstrap 模式中的 Quill 编辑器中?
- sql - 透视 SQL Server 表
- javascript - 如何使用 If () javascript 检查类是否被点击
- java - Android Studio com.google.wireless.android.sdk.stats.IntellijIndexingStats
- azure - Azure devops 构建推送映像到 aks
- wordpress - 如何检查文件是否真的存在于 WordPress 中?
- php - 未定义的变量:注释 - Laravel 5.8