简体   繁体   English

如何在不覆盖预先保存的数据的情况下将更多内容写入文件

[英]How to write more into a file without overwriting on pre-saved data

i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data. 我创建了一个文件,当我运行该程序时,数据被写入文件中,但是当我再次运行该程序时,新数据覆盖了旧数据。 i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file. 我需要一旦程序运行并收集数据,这些数据就可以彼此级联地写入文件,而不会覆盖文件中的先前数据。

this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon. 这段代码运行成功,但是当我再次运行该程序时,发生了我不需要的覆盖工作,我需要将先前的数据保存在文件旁边,并在其后不久写入新数据。

public class MainActivity extends Activity {
File file;
String sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FlieName = "Output1.txt";
EditText txtData;
Button btnWriteSDFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtData = (EditText) findViewById(R.id.editText1);
    btnWriteSDFile = (Button) findViewById(R.id.button1);
    btnWriteSDFile.setOnClickListener(new OnClickListener() 
    {
        public void onClick(View v)
        { 
            try {
                file = new File("/sdcard/Output1.txt");
                file.createNewFile();
                fos = new FileOutputStream(file);

                String eol = System.getProperty("line.separator");
                myOutWriter =new OutputStreamWriter(fos);
                myOutWriter.append(txtData.getText() + eol);// write from editor 
                myOutWriter.close();
                fos.close();
                Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
                txtData.setText("");
            } catch (Exception e) {
                // e.printStackTrace();
                Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }
    });

}

} }

First, you are calling createNewFile() . 首先,您要调用createNewFile() This indicates that you want to create a new file. 这表明您要创建一个新文件。 If you do not want to create a new file, do not call createNewFile() . 如果您不想创建新文件,请不要调用createNewFile() And, since the documentation for createNewFile() says "This method is not generally useful", you may wish to consider just getting rid of it. 而且,由于createNewFile()的文档说“此方法通常没有用”,因此您可能希望考虑摆脱它。

Second, you need to indicate that you want to append to the existing data when you open and use that file. 其次,在打开和使用该文件时,需要指出要附加到现有数据上。 The standard recipe for this: 为此的标准配方

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //oh noes!
}

The true in the second parameter to the FileWriter constructor indicates that you want to append instead of overwrite. FileWriter构造函数的第二个参数中的true表示您要追加而不是覆盖。

Third, do not hardcode paths in Android . 第三, 不要在Android中对路径进行硬编码 /sdcard/Output1.txt has been poor form for years and will not work on some Android devices. /sdcard/Output1.txt格式不/sdcard/Output1.txt已有多年,在某些Android设备上无法使用。

Fourth, do not clutter up the root of external storage. 第四,不要弄乱外部存储的根源。 Hence, instead of: 因此,代替:

file = new File("/sdcard/Output1.txt");

use: 采用:

file = new File(getExtenalFilesDir(null), "Output1.txt");

to put the file in a subdirectory unique for your own app. 将文件放在您自己的应用唯一的子目录中。

Try using java.nio. 尝试使用java.nio。 Files along with java.nio.file. 文件以及java.nio.file。 StandardOpenOption StandardOpenOption

try(BufferedWriter bufWriter =
        Files.newBufferedWriter(Paths.get("/sdcard/Output1.txt"),
            Charset.forName("UTF8"),
            StandardOpenOption.WRITE, 
            StandardOpenOption.APPEND,
            StandardOpenOption.CREATE);
    PrintWriter printWriter = new PrintWriter(bufWriter, true);)
{ 

    printWriter.println("Text to be appended.");

}catch(Exception e){
    //Oh no!
}

This uses a try-with-resources statement to create a BufferedWriter using Files, which accepts StandardOpenOption parameters, and an auto-flushing PrintWriter from the resultant BufferedWriter . 这使用try-with-resources语句使用Files创建一个BufferedWriter ,该文件接受StandardOpenOption参数,并从生成的BufferedWriter自动刷新PrintWriter PrintWriter 's println() method, can then be called to write to the file. 然后可以调用PrintWriterprintln()方法来写入文件。

The StandardOpenOption parameters used in this code: opens the file for writing, only appends to the file, and creates the file if it does not exist. 此代码中使用的StandardOpenOption参数:打开要写入的文件,仅追加到文件,如果不存在则创建文件。

Paths.get("path here") can be replaced with new File("path here").toPath() . 可以将Paths.get("path here")替换为new File("path here").toPath() And Charset.forName("charset name") can be modified to accommodate the desired Charset . 并且可以修改Charset.forName("charset name")以容纳所需的Charset

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在文件中写入多个文本而不会覆盖它 - How to write multiple text in file without overwriting it 如何在不覆盖的情况下写入文本文件? - how to write to a text file without overwriting? Spring:将带有数据的对象从控制器传递到jsp,并从Spring Form Submit取回预先保存的数据 - Spring: pass object with data from controller to jsp and get the pre-saved data back from Spring Form submit 如何在Java NetBeans中创建新的“ .txt”文件而不覆盖以前保存的文件? - how can i create a new “.txt” file in java netbeans without overwriting the previous saved file? 如何将数据保存在文件中而不覆盖该文件中的旧数据? - How to save data in a file without overwriting the old data in that file? 写入文本文件而不覆盖先前的条目 - Write to text file without overwriting previous entry 写入文本文件而不用Java覆盖 - Write to text file without overwriting in Java 如何在不覆盖该文件中的信息的情况下使用 spring 批处理将标题和尾部写入现有文件? - How do I write a header and trailer to an existing file using spring batch without overwriting the information in that file? 如何在不覆盖 Java 中的当前内容的情况下写入外部文本文件 - How can I write to an external text file without overwriting current content in Java 如何在不覆盖现有数据的情况下添加数据? - How to add data without overwriting the existing data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM