使用以下代码,Google 云端硬盘上的文本文件将按预期首先删除,仅在文件中保留新写入的内容。如果文件位于 OneDrive 上,前 x 个字节将被覆盖,其余原始字节保持不变。有谁知道 OneDrive 文件的解决方法。我需要删除旧内容,只保留写入的新内容。
根据这些文档 openAssetFileDescriptor和 openAssetFile 这就是应该发生的事情。
我已经使用 Java/Android Studio 和 C#/Xamarin、Android 手机 9 api 28 尝试过此操作。
public void saveFile(View view)
{
try
{
AssetFileDescriptor pfd = getContentResolver().openAssetFileDescriptor(fileUri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(("Overwritten again " + System.currentTimeMillis() + "\n").getBytes());
fileOutputStream.close();
pfd.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
无法想出为什么它不能按照记录的方式工作,但我已经想出了一种解决方法来模拟预期的行为。如果有人看到更好的方法,不介意评论。
public void saveFile(View view)
{
try
{
ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(fileUri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
//Added if-block to simulate automatic truncate when file located on onedrive.
if( (fileUri.toString()).contains("skydrive"))
{
FileChannel fileChannel = fileOutputStream.getChannel();
fileChannel.truncate(0);
}
fileOutputStream.write(("Overwritten again " + System.currentTimeMillis() + "\n").getBytes());
fileOutputStream.close();
pfd.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
关于java - openAssetFileDescriptor 不会截断 OneDrive 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059311/