gpt4 book ai didi

java - DocumentFile 随机访问文件

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:44:04 28 4
gpt4 key购买 nike

有没有办法从给定的 DocumentFile 中获取 RandomAccessFile

我知道可以通过 getUri 获取 InputStream

InputStream inputStream = getContentResolver().openInputStream(DocumentFile.getUri());

但我需要一个RandomAccessFile

谢谢你的帮助,

詹斯

最佳答案

对于 SDK 21 (Lollipop) 来说,获得对 SD 卡上文件的随机读/写访问权限的唯一方法似乎如下:

import android.content.Context;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import com.jetico.bestcrypt.FileManagerApplication;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class SecondaryCardChannel {//By analogy with the java.nio.channels.SeekableByteChannel
private FileChannel fileChannel;
private ParcelFileDescriptor pfd;
private boolean isInputChannel;
private long position;

public SecondaryCardChannel(Uri treeUri, Context context) {
try {
pfd = context.getContentResolver().openFileDescriptor(treeUri, "rw");
FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
fileChannel = fis.getChannel();
isInputChannel = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public int read(ByteBuffer buffer) {
if (!isInputChannel) {
try {
fileChannel.close();
FileInputStream fis = new FileInputStream(pfd.getFileDescriptor());
fileChannel = fis.getChannel();
isInputChannel = true;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileChannel.position(position);
int bytesRead = fileChannel.read(buffer);
position = fileChannel.position();
return bytesRead;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}

public int write(ByteBuffer buffer) {
if (isInputChannel) {
try {
fileChannel.close();
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
fileChannel = fos.getChannel();
isInputChannel = false;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileChannel.position(position);
int bytesWrite = fileChannel.write(buffer);
position = fileChannel.position();
return bytesWrite;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}

public long position() throws IOException {
return position;
}

public SecondaryCardChannel position(long newPosition) throws IOException {
position = newPosition;
return this;
}

public long size() throws IOException {
return fileChannel.size();
}

public SecondaryCardChannel truncate(long size) throws IOException {
fileChannel.truncate(size);
return this;
}
}

关于java - DocumentFile 随机访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28897329/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com