如何在 Android PrintService 中访问与 PrintJob 对象关联的文件?
How to Access the file associated with PrintJob Object in an Android PrintService?
我已经遵循了这个 PrintService
示例存储库中的很多代码:Zaki50 PrintService。我试图做的唯一不同的事情是从与 PrintJob
关联的文件中获取字节。现在我有了 FileDescriptor
,但不知道如何使用它来获取实际的文件数据!任何帮助将不胜感激。
好的,这是代码中的答案:
final PrintJobInfo info = printJob.getInfo();
final File file = new File(getFilesDir(), info.getLabel());
InputStream in = null;
FileOutputStream out = null;
try {
in = new
FileInputStream(printJob.getDocument().getData().getFileDescriptor());
out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (IOException ioe) {
}
FileChannel channel = null;
byte[] fileBytes = null;
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
ByteBuffer bb = ByteBuffer.NEW(channel.map(
FileChannel.MapMode.READ_ONLY, 0, channel.size()));
fileBytes = new byte[bb.remaining()];
bb.get(fileBytes , 0, fileBytes .length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fileBytes
数组的内容是打印文件的实际字节数。
我已经遵循了这个 PrintService
示例存储库中的很多代码:Zaki50 PrintService。我试图做的唯一不同的事情是从与 PrintJob
关联的文件中获取字节。现在我有了 FileDescriptor
,但不知道如何使用它来获取实际的文件数据!任何帮助将不胜感激。
好的,这是代码中的答案:
final PrintJobInfo info = printJob.getInfo();
final File file = new File(getFilesDir(), info.getLabel());
InputStream in = null;
FileOutputStream out = null;
try {
in = new
FileInputStream(printJob.getDocument().getData().getFileDescriptor());
out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.flush();
out.close();
} catch (IOException ioe) {
}
FileChannel channel = null;
byte[] fileBytes = null;
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
ByteBuffer bb = ByteBuffer.NEW(channel.map(
FileChannel.MapMode.READ_ONLY, 0, channel.size()));
fileBytes = new byte[bb.remaining()];
bb.get(fileBytes , 0, fileBytes .length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fileBytes
数组的内容是打印文件的实际字节数。