我想同时将两个字符串保存到一个文本文件中。其中一个字符串不断输入数据,而另一个字符串仅在单击按钮时写入数据。但是,当我单击按钮将值从那里添加到txt文件时,它会写入,但它会删除之前的其他字符串中的所有数据。之后,另一个字符串恢复正常写入。
以下是打印到文件的两个字符串的代码:
public void onClick(View view) {
try {
EditText bodyText;
bodyText = (EditText) findViewById(R.id.ETName);
String name = bodyText.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html")));
out.println("<h3 style=padding-left:20px;>" + name
+ "</h3><br>");
// new arraylist
out.close();
} catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
e.printStackTrace();
}
}
});
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
writer.println("<h3 style=padding-left:20px;>" + text
+ "</h3><br>");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
任何帮助都会很棒,谢谢。
答案 0 :(得分:0)
修正了它:
Button confirmButton = (Button) findViewById(R.id.baddNametoFile);
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
try {
EditText bodyText;
bodyText = (EditText) findViewById(R.id.ETName);
String name = bodyText.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
out.println("<h3 style=padding-left:20px;>" + name
+ "</h3><br>");
out.close();
} catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
e.printStackTrace();
}
}
});
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
writer.println("<h3 style=padding-left:20px;>" + text
+ "</h3><br>");
// new arraylist
writer.close();
} catch (IOException e) {
// put notification here later!!!
e.printStackTrace();
}
}
基本上,我想要两个字符串保存到一个文件,然后共存于文件中(不覆盖等等)。我的第一个代码示例放在一个字符串中,然后用另一个字符串覆盖它。新代码现在将两个字符串写成相同,因此不会相互覆盖。