如何测试文件是否存在于 SDCard 上?
How to test if file exists on an SDCard?
我正在尝试将 PDF 文件从我的应用程序的私有存储复制到 SD 卡,以便其他 PDF 程序可以打开它。我的问题是测试文件是否存在。如果测试 file.exists() 为真,我将不会再次复制该文件。问题是当条件为真时,android 显示一条消息,指出我的文件不是有效的 PDF 文件
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ac8.pdf");
try {
in = assetManager.open("ac8.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
if (file.exists()) {
Toast.makeText(getApplicationContext(), "File already exist", Toast.LENGTH_LONG).show();
} else {
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
} catch(Exception e)
{
Log.e("tag", e.getMessage());
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/ac8.pdf"),
"application/pdf");
startActivity(intent);
} catch (Exception e){
Toast.makeText(getApplicationContext(), "No PDF application found", Toast.LENGTH_LONG).show();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
第三方应用无法访问您应用的 internal storage(例如,getFilesDir()
目录)。或者:
将文件写入external storage,或
将文件保留在内部存储中,然后 use FileProvider
通过 content://
Uri
将文件提供给第三方 PDF 查看器
您可以在 the documentation 中阅读有关第二种方法的更多信息。
我正在尝试将 PDF 文件从我的应用程序的私有存储复制到 SD 卡,以便其他 PDF 程序可以打开它。我的问题是测试文件是否存在。如果测试 file.exists() 为真,我将不会再次复制该文件。问题是当条件为真时,android 显示一条消息,指出我的文件不是有效的 PDF 文件
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "ac8.pdf");
try {
in = assetManager.open("ac8.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
if (file.exists()) {
Toast.makeText(getApplicationContext(), "File already exist", Toast.LENGTH_LONG).show();
} else {
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
} catch(Exception e)
{
Log.e("tag", e.getMessage());
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/ac8.pdf"),
"application/pdf");
startActivity(intent);
} catch (Exception e){
Toast.makeText(getApplicationContext(), "No PDF application found", Toast.LENGTH_LONG).show();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
第三方应用无法访问您应用的 internal storage(例如,getFilesDir()
目录)。或者:
将文件写入external storage,或
将文件保留在内部存储中,然后 use
FileProvider
通过content://
Uri
将文件提供给第三方 PDF 查看器
您可以在 the documentation 中阅读有关第二种方法的更多信息。