【发布时间】:2018-04-05 12:18:14
【问题描述】:
所以,我想要实现的是将回收站视图内容保存在 pdf 文件中。我已经使用 PDFDocument 类 来实现这一点。我已经添加了权限。
使用权限 android:name="android.permission.WRITE_EXTERNAL_STORAGE"
我不知道我在这里做错了什么。我曾尝试更改存储的位置,但每次都出现相同的错误。
如果有人能告诉我我在这里做错了什么。下面是相关代码:
if (selectedId == R.id.action_save_pdf) {
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PdfDocument.PageInfo pageInfo =
new PdfDocument.PageInfo.Builder(100, 100, 1).create();
// start a page
PdfDocument.Page page = document.startPage(pageInfo);
// finish the page
document.finishPage(page);
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/MyPDFDocument");
if (!dir.exists()) {
dir.mkdir();
}
File filePath = new File(dir, "questions.pdf");
try {
document.writeTo(new FileOutputStream(filePath));
Toast.makeText(this, "Saved to PDF", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Unsuccessful!",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "External Storage not available!", Toast.LENGTH_SHORT).show();
}
// close the document
document.close();
return true;
}
return super.onOptionsItemSelected(item);
}
提前谢谢你。
【问题讨论】:
-
我认为这行
File filePath = new File(dir, "questions.pdf");创建了必要的文件。 -
@sunilsunny 我试着按照你说的去做。还是一样的错误
-
if (!dir.exists()) { dir.mkdir(); }那应该是:if (!dir.exists()) { if ( !dir.mkdir()) {Toast(... could not make dir ....); return;}; }。我床的目录没有创建。 -
@sunil Sunny
There should be something like filePath.createNewFile(); then only that file will be created. – sunil sunny 56 mins ago。废话。new FileOutputStream(filePath)将创建文件。好吧,如果目录存在并授予权限。 -
thought this line File filePath = new File(dir, "questions.pdf"); creates the necessary file.不,不会。但也不需要。