Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何写入文件,而不是在android中重写?_Android_File - Fatal编程技术网

如何写入文件,而不是在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

我有android应用程序,其中有一些变量。我想在点击按钮后将每条消息写入文件。我怎么做?每次点击按钮后,我都会调用这个方法

但是这个代码总是重写我的文件。。。我试过谷歌,但到处都是重写

    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();
    }