如何写入文件,而不是在android中重写?
我有android应用程序,其中有一些变量。我想在点击按钮后将每条消息写入文件。我怎么做?每次点击按钮后,我都会调用这个方法 但是这个代码总是重写我的文件。。。我试过谷歌,但到处都是重写如何写入文件,而不是在android中重写?,android,file,Android,File,我有android应用程序,其中有一些变量。我想在点击按钮后将每条消息写入文件。我怎么做?每次点击按钮后,我都会调用这个方法 但是这个代码总是重写我的文件。。。我试过谷歌,但到处都是重写 try { String fpath = "/sdcard/"+"NAME"+".txt"; File file = new File(fpath); // If file does not exists, then create it i
try {
String fpath = "/sdcard/"+"NAME"+".txt";
File file = new File(fpath);
// If file does not exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(msg);
bw.close();
//Log.d("Suceess", "Sucess");
} catch (IOException e) {
e.printStackTrace();
}
尝试
根据传递的
true
,构造函数上的第二个参数使其附加到文件,而不是重写 您还可以使用RandomAccessFile
附加文本:
try {
RandomAccessFile raf = new RandomAccessFile(yourTxt.getAbsolutePath(), "rw");
if (txt.length() > 0) {
raf.seek(txt.length());
raf.write("\n".getBytes());
raf.write(yourString.getBytes());
raf.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
顺便说一下,使用搜索
try {
RandomAccessFile raf = new RandomAccessFile(yourTxt.getAbsolutePath(), "rw");
if (txt.length() > 0) {
raf.seek(txt.length());
raf.write("\n".getBytes());
raf.write(yourString.getBytes());
raf.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}