Android 此方法写入文件是否正确?
我在安卓工作室工作。我使用下面的代码在文件中写入,但文件不工作。有人能告诉我为什么这个代码不起作用吗Android 此方法写入文件是否正确?,android,android-studio,file-writing,Android,Android Studio,File Writing,我在安卓工作室工作。我使用下面的代码在文件中写入,但文件不工作。有人能告诉我为什么这个代码不起作用吗 try { FileWriter fileWriter = new FileWriter("accounts.txt",true); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write(tvUername.getText().toStr
try {
FileWriter fileWriter = new FileWriter("accounts.txt",true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(tvUername.getText().toString()+","+tvEmail.getText().toString()+","+tvCPassword.getText().toString()+"\n");
Toast.makeText(SignUpActivity.this, "account saved", Toast.LENGTH_SHORT).show();
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
我认为你的代码很好。但如果不起作用: 使用下面的代码,它在文件中工作
File rootStorage = new File(String.valueOf(getApplicationContext().getExternalFilesDir("storage/emulated/0")));
String actualFileName = new File(rootStorage.getAbsolutePath() + "/" + fileName)
try {
File textFile = new File(actualFileName);
if (textFile.exists()) {
System.out.println("File path exists = " + textFile.getAbsolutePath());
// set to true if you want to append contents to text file
// set to false if you want to remove preivous content of text
// file
FileWriter textFileWriter = new FileWriter(textFile, true);
BufferedWriter out = new BufferedWriter(textFileWriter);
// create the content string
String contentString = new String(contents);
// write the updated content
out.write(contentString);
out.close();
System.out.println("Updaetd text file");
}
如果需要创建一个新文件,请编写,然后使用以下代码:
try {
File file = new File(actualFileName);
if (!file.exists()) {
System.out.println("File path = " + file.getAbsolutePath());
if (file.createNewFile()) {
Toast.makeText(this, "File Name is sampleDeveloper.txt", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "File not Created", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
FileWriter需要一个完整的路径。您能定义“不工作”吗?File rootStorage=new File(String.valueOf(getApplicationContext().getExternalFilesDir(“存储/模拟的/0”));String actualFileName=新文件(rootStorage.getAbsolutePath()+“/”+文件名)<代码>文件根存储=新文件(String.valueOf(getApplicationContext().getExternalFilesDir(“存储/模拟的/0”))对不起,那是胡说八道。或者使用:
File rootStorage=Environment.getExternalStorageDirectory()
或使用文件rootStorage=getExternalFilesDir(null)代码>`File textFile=新文件(实际文件名)代码>更好:文件textFile=新文件(根路径,文件名)代码>多种方式。。。。。。由你决定,你喜欢什么都行。