ParcelFileDescriptor使用说明

文件描述符,是一种程序读写已打开文件、socket 的对象。

FileDescriptor 对象,它代表了原始的 Linux 文件描述符
ParcelFileDescriptor 对象,是原始文件描述符的一个复制,对象跟 fd 不同,但都是操作同一个底层文件流以及文件位置指针

简单的 ParcelFileDescriptor 使用——pipe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public class DemoParcefliledescriptor extends AppCompatActivity {

private static final String TAG = "DemoPFD";

private static final String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
private static final int PERMISSIONS_CODE = 3006;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_null);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(PERMISSIONS, PERMISSIONS_CODE);
}

FileOutputStream outputStream = new FileOutputStream(getStreamFd());
try {
outputStream.write(99);
outputStream.write(98);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}


private FileDescriptor getStreamFd() {
ParcelFileDescriptor[] pipes = null;

try {
pipes = ParcelFileDescriptor.createPipe();
new TransferThread(new ParcelFileDescriptor.AutoCloseInputStream(pipes[0])).start();
} catch (IOException e) {
e.printStackTrace();
}

return pipes[1].getFileDescriptor();
}

static class TransferThread extends Thread {
InputStream in;
FileOutputStream out;

TransferThread(InputStream in, FileOutputStream out) {
this.in = in;
this.out = out;
}

TransferThread(InputStream in) {
this.in = in;

File outFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/zlq_pdf");
Log.i(TAG, "File: " + outFile.getAbsolutePath());

try {
out = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

@Override
public void run() {
byte[] buf = new byte[1024*2];

int len;
try {
while((len=in.read(buf)) > 0) {
out.write(buf, 0, len);
Log.i(TAG, "out:" + len);

}

in.close();
out.flush();
out.getFD().sync();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
发布于

2022-09-05

更新于

2023-08-18

许可协议

评论