Android开发:如何在for循环中将字符串数组内容写入单个文件?
解决Android中多条数据写入同一文件的问题
我来帮你搞定这个问题!你当前的核心问题是在循环里每次调用writeToFile()方法,这会导致每次循环都创建一个新文件并只写入单条数据,自然就生成了多个独立文件。我们只需要调整逻辑,先把所有内容整合好,再一次性写入同一个文件即可。
修改步骤及代码示例
1. 调整点击事件中的数据收集逻辑
把循环内的文件写入操作移到循环外,先将所有需要写入的内容拼接起来:
public void onClick(DialogInterface dialogInterface, int i) { final Request request = new Request(Common.currentUser.getPhone(), edtAddress.getText().toString(), Common.currentUser.getName(), txtTotalPrice.getText().toString(), "0", edtComment.getText().toString(), cart); requests.child(String.valueOf(System.currentTimeMillis())) .setValue(request); // 使用StringBuilder高效拼接所有行内容(比数组更适合动态拼接) StringBuilder fileContent = new StringBuilder(); // 循环变量改用j,避免和方法参数的i冲突 for (int j = 0; j < cart.size(); j++) { String codebar = cart.get(j).getCodebar(); String quantity = cart.get(j).getQuantity(); // 修正了字符串中的引号转义问题(Java中需要用\"表示双引号) String nuevo = format + ", " + convertCodeToMonth(month) + ", " + request.getPhone() + ", \"01\", \"2\", \"3\", " + codebar + "," + quantity; // 每条内容后添加换行符,让数据按行分隔 fileContent.append(nuevo).append("\n"); Log.d("INFOOOOOOOOOOO", "onClick: "+nuevo); } // 循环结束后,一次性写入所有内容到同一个文件 writeToFile(fileContent.toString()); new Database(getBaseContext()).cleanCart(); Toast.makeText(Cart.this, "Gracias por su compra", Toast.LENGTH_SHORT).show(); finish(); }
2. 保持writeToFile方法的逻辑(无需大幅修改)
这个方法现在接收完整的拼接内容,只执行一次文件创建和写入操作,确保所有数据都写入同一个文件:
private void writeToFile(String s) { // 用当前时间生成唯一文件名,避免重复 final File archivo = new File(filePaths.FILES, format + String.valueOf(System.currentTimeMillis()) + ".txt"); Log.d("WRITING", "writeToFile: "+filePaths.FILES); try { archivo.createNewFile(); FileOutputStream fOut = new FileOutputStream(archivo); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(s); myOutWriter.close(); fOut.flush(); fOut.close(); } catch (IOException e){ Log.e("Exception", "writeToFile: "+e.toString() ); } }
关键修改点说明
- 移除循环内的
writeToFile调用:避免重复创建文件,把文件操作集中到循环结束后执行。 - 使用
StringBuilder拼接内容:相比数组,它更适合动态添加字符串,性能也更优。 - 添加换行符
\n:让每条数据单独占一行,方便后续读取和查看文件内容。 - 修正字符串引号问题:原代码中的
"01"在Java中会导致编译错误,需要转义为\"01\"。
内容的提问来源于stack exchange,提问作者Adan_004
相关产品推荐
相关产品推荐

