我尝试了不同的代码,但似乎都不起作用。删除将进入同一目录。它可以检测该文件。它还会误报已删除,但当提示打开文件时,文件中的文本打开时没有任何问题。是文件没有被删除还是文件保存在内存中?如果不删除文件就可以了。我只是想删除里面的内容,它是一个文本文件。
这是我当前正在使用的代码:
File dir = getFilesDir();
File file = new File(dir, n);
deleteFile(n);
我之前尝试过此代码来删除数据或修改数据,但它也不起作用:
FileOutputStream fos = null;
try {
fos = openFileOutput(name1, MODE_PRIVATE);
fos.write(save.getBytes());
Toast.makeText(Home2.this,
"Saved to " + getFilesDir() + "/" + name1,
Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想完全删除其中的所有文本并删除该文件(如果可能的话)。
此代码将打开文件,擦除其内容,然后根据需要删除该文件:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
// ...
// Define the file name
String fileName = "your_text_file.txt";
// Get the file object
File file = new File(getFilesDir(), fileName);
try {
// Open the file for writing, this will erase its content
FileWriter writer = new FileWriter(file);
// Optionally, delete the file after erasing its content
boolean deleteFileAfterErase = true;
// If you want to delete the file, uncomment the next line
// deleteFileAfterErase = file.delete();
writer.close();
if (deleteFileAfterErase) {
// The file is deleted after erasing its content
Toast.makeText(Home2.this, "File content erased and deleted.", Toast.LENGTH_LONG).show();
} else {
// The file content is erased, but the file is not deleted
Toast.makeText(Home2.this, "File content erased.", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Home2.this, "Error erasing file content.", Toast.LENGTH_LONG).show();
}
此代码首先以写入模式打开文件,擦除文件的内容。然后,您可以通过将
deleteFileAfterErase
变量设置为 true 或 false 来选择在清除内容后是否删除文件。
如果将
deleteFileAfterErase
设置为 true,则文件的内容将被删除,如果设置为 false,则仅删除内容并保留空文件。