Java 测试文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2786655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if file exists
提问by rantravee
I'm trying to open a file in android like this :
我正在尝试在 android 中打开一个文件,如下所示:
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
,但如果文件不存在,则会引发文件未找到异常。我想知道如何在尝试打开文件之前测试该文件是否存在。
回答by rompetroll
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
文档说 Context.openFileInput 要么返回一个 inputStream(找到文件)要么抛出一个 FileNotFoundException(未找到)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
所以看起来例外是你的“测试”。
You could also try using standard
您也可以尝试使用标准
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get deleted when your app gets uninstalled.
但不建议这样做。Context.openFileInput() 和 Context.openFileOutput() 确保您留在设备上的应用程序存储上下文中,并且当您的应用程序被卸载时,您的所有文件都会被删除。
回答by Prashast
why dont you just catch the FileNotFound exception and take that as the file not being present.
为什么不只是捕获 FileNotFound 异常并将其视为文件不存在。
回答by lencinhaus
I think the best way to know if a file exists, without actually trying to open it, is as follows:
我认为无需实际尝试打开文件即可知道文件是否存在的最佳方法如下:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
Hope that helps, bye!
希望有帮助,再见!
回答by tjb
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
如果您想在任何情况下打开一个文件(即,如果它不存在,则创建一个新文件,如果它确实附加到旧文件),您可以使用它,无需测试:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
回答by Sameer Chorge
My suggestion is to check length of the file. if file.length() returns 0
that means file doesn't exist.
我的建议是检查文件的长度。if file.length() returns 0
这意味着文件不存在。
回答by molbalga
With the standard java.io.File
this is the function I have created, and works correctly:
使用标准,java.io.File
这是我创建的功能,并且可以正常工作:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
回答by Den-Jason
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
如果你想确保一个文件存在(即如果它不存在则创建一个新的,如果存在则不要删除它)然后使用 File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
例如
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}