[英]How to stop a file from overwriting itself when using FileOutputStream using openFileOutput in Android
I'm currently making an app that needs to save the number and write it into a text file.我目前正在制作一个需要保存数字并将其写入文本文件的应用程序。 But every time it writes to the file.
但每次写入文件时。 It overwrites the last things saved.
它会覆盖上次保存的内容。 Here is the code of the entire program in java.
下面是整个程序在java中的代码。
package com.galaxy.nestetrisscores;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileOutputStream;
import java.io.File;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editNumber;
private String file = "Scores.txt";
private String fileContents;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editNumber = findViewById(R.id.editNumber);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fileContents = editNumber.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE);
fOut.write(fileContents.getBytes());
fOut.close();
File fileDir = new File(getFilesDir(), file);
Toast.makeText(getBaseContext(), "File Saved at" + fileDir, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
}
构造FileOutputStream
时使用附加模式。
FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE | MODE_APPEND);
Not sure if this will be of any use, but a simple IF using the .exists() boolean method不确定这是否有任何用处,但使用 .exists() 布尔方法的简单 IF
File file = new File("file.txt");
if (file.exists()) {
System.err.println("File already exists");
// Append to file
} else {
// Create File
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.