java - 实时写入并删除文件 JAVA 中的最后一个字符
问题描述
我在 json 中转换一个 txt,我正在使用 json-simple。我希望文件是实时写入的,即每一行,为此我选择不使用JsonArray,因为如果我使用JSONArray,我必须先等待它完成,然后将其写入文件. 所以我只使用 JsonObjects。我必须创建一个“隐藏”JsonArray 的问题,为此我在文件的开头和结尾添加方括号,然后在每个 JsonObject 中添加一个逗号。即使在“]”之前的文件末尾也明显打印逗号的问题,如何删除最后一个逗号?
br = new BufferedReader(new FileReader(pathFile + ".txt"));
JSONObject stringDetails = new JSONObject();
JSONArray stringList = new JSONArray();
try (FileWriter file = new FileWriter(pathfile+".json",true)) {
file.write("[");
while ((line = br.readLine()) != null) {
//Miss the code to convert from txt string to json string ...
stringDetails.put(stringJson.getKey(), stringJson.getMessage());
file.write(String.valueOf(stringDetails)+",");
stringDetails = new JSONObject();
}
file.write("]");
}
另一个问题是,使用 append(true),如果程序以异常方式停止,之前的所有字符串都保存了吗?
非常感谢。
解决方案
我看到了两种可能的方法,这两种方法都是首先不打印它的解决方案。
第一:boolean
在while循环中使用a和if语句来打印条目之前的逗号(第一个除外)
boolean isFirst = true;
file.write("[");
while ((line = br.readLine()) != null) {
//Miss the code to convert from txt string to json string ...
stringDetails.put(stringJson.getKey(), stringJson.getMessage());
if (isFirst) {
isFirst = false;
} else {
// print the comma before the new entry
file.write(",");
}
file.write(String.valueOf(stringDetails));
stringDetails = new JSONObject();
}
file.write("]");
第二:第二种方法是使用私有帮助方法来打印文件的条目,例如:
private static void printEntry(FileWriter file, String line, ... /* what ever else you need*/) {
//Miss the code to convert from txt string to json string ...
stringDetails.put(stringJson.getKey(), stringJson.getMessage());
file.write(String.valueOf(stringDetails));
stringDetails = new JSONObject();
}
并使用它从 while 循环中提取第一个条目的写入,例如:
file.write("[");
if ((line = br.readLine()) != null) {
// print first entry
printEntry(file, line, ...);
// print the rest
while ((line = br.readLine()) != null) {
file.write(",");
printEntry(file, line, ...);
}
}
file.write("]");
推荐阅读
- shell - 如何用引号 grep 特定行,然后比较其中的内容
- tpm - Tpm 2.0 取得所有权不创建 SRK
- android - 为什么这个 kotlin 分配可能(switchButton.isChecked = true)
- c - 编程C的执行结果并不顺利。为什么?
- python - 获取scipy的solve_ivp函数执行中间任务
- sql-server - 对于 sql server,我想选择所有已更改的记录
- python - Google App Engine 不为我在 app.yaml 中定义的入口点提供服务
- sql - 在 Postgresql 中将 UUlD 存储为 VARCHAR 而不进行任何格式化
- mobaxterm - 如何在 Mobaxterm 上使用自定义语法高亮
- amazon-web-services - Glue Boto 客户端——NoCredentialsError