Java 如何在文件末尾添加数字?
我正在尝试将文本文件写入外部存储器,我想知道如何附加到文件名,以便存储唯一的文件而不覆盖过去的文件 同样,我在android studio上的文件资源管理器中看到了该文件,但在手机上找不到它,当我使用模拟器时也会发生同样的情况,我在文件资源管理器中看不到它,但在使用设备资源管理器时可以验证它是否存在 我的代码:Java 如何在文件末尾添加数字?,java,android,android-file,android-external-storage,Java,Android,Android File,Android External Storage,我正在尝试将文本文件写入外部存储器,我想知道如何附加到文件名,以便存储唯一的文件而不覆盖过去的文件 同样,我在android studio上的文件资源管理器中看到了该文件,但在手机上找不到它,当我使用模拟器时也会发生同样的情况,我在文件资源管理器中看不到它,但在使用设备资源管理器时可以验证它是否存在 我的代码: import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
Button btnSave, btnLoad;
EditText etInput;
TextView tvLoad;
String fileName = "";
String filePath = "";
String fileContent = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSave = findViewById(R.id.buttonSave);
btnLoad = findViewById(R.id.buttonLoad);
etInput = findViewById(R.id.etInput);
tvLoad = findViewById(R.id.tvLoad);
fileName = "myFile.txt";
filePath = "myFileDir";
if(!isExternalStorageAvailableForRW()){
btnSave.setEnabled(false);
}
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvLoad.setText("");
fileContent = etInput.getText().toString().trim();
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filePath), fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
etInput.setText("");
Toast.makeText(MainActivity.this,"File Saved, check dir", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"Textfield empty", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isExternalStorageAvailableForRW() {
String extStorageState = Environment.getExternalStorageState();
if(extStorageState.equals(Environment.MEDIA_MOUNTED)){
return true;
}
return false;
}
}
为了
Java 7+
对于一次性任务,“文件”类使此操作变得简单:
try {
Files.write(Paths.get("filePath"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
上述方法将抛出一个错误
NoSuchFileException
如果文件不存在。它也不会自动追加换行符(在追加到文本文件时,通常需要这样做)。另一种方法是传递CREATE和APPEND选项,如果文件不存在,则会首先创建文件:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filePath"),
s + System.lineSeparator(),
CREATE, APPEND
);
}