我在尝试将字符串添加到数组然后写入文件时遇到问题,使用此代码我可以编写文件,但每个字符串保存1个文件,我需要将其保存为列表如何解决此问题问题是只在for语句中为所有字符串创建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);
String[]resultado=new String[cart.size()];
for ( i=0;i<cart.size();i++) {
String codebar = cart.get(i).getCodebar();
String quantity = cart.get(i).getQuantity();
//THIS LINE BELOW IS THE ONE I NEED TO HAVE IN TXT FILE
String nuevo =format+", "+convertCodeToMonth(month)+", "+request.getPhone()+", "+"01"+", "+"2"+", "+"3"+", "+codebar+","+quantity;
//THIS LINE BELOW SUPPOSED TO RECEIVE THE STRINGS
resultado[i]=nuevo;
//THIS LINE BELOW SUPPOSED TO WRITE TO FILE
writeToFile(resultado[i]);
Log.d("INFOOOOOOOOOOO", "onClick: "+resultado[i]);
}
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Gracias por su compra", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
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() );
}
}
答案 0 :(得分:1)
您需要在writeToFile方法之外创建此文件!然后你可以在方法中引用它,并且每次都不会创建一个新的。
答案 1 :(得分:1)
您可以使用StringBuilder而不是数组吗?这将允许您构建1个单个String对象,准备保存到您的文件中......
StringBuilder resultado = new StringBuilder();
for ( i=0;i<cart.size();i++) {
String codebar = cart.get(i).getCodebar();
String quantity = cart.get(i).getQuantity();
//THIS LINE BELOW IS THE ONE I NEED TO HAVE IN TXT FILE
String nuevo =format+", "+convertCodeToMonth(month)+", "+request.getPhone()+", "+"01"+", "+"2"+", "+"3"+", "+codebar+","+quantity;
//append the new data, and a line break :
resultado.append(nuevo);
resultado.append("\n");
Log.d("INFOOOOOOOOOOO", "onClick: "+nuevo);
}
writeToFile(resultado.toString());