Android开放文件 [英] Android open file
问题描述
我试图打开一个文件进行读取。
i was trying to open a file for reading..
使用扫描仪输入=新的扫描仪(文件名);
文件找不到
但是当我用
InputStream in = openFileInput(filename);
Scanner input = new Scanner(in);
它的工作...为什么是code中的第一行错了吗?
it worked...why was the first line of code wrong?
推荐答案
文件存储在设备上的一个特定的,依赖于应用程序的位置,这是我想 openFileInput
加在文件名的开头。最后的结果(位置+文件名)的结构如下:
Files are stored on the device in a specific, application-dependent location, which is what I suppose openFileInput
adds at the beginning of the file name. The final result (location + file name) is constructed as follows:
/data/data/<application-package>/files/<file-name>
还要注意文件指出 openFileInput
参数<一href="http://developer.android.com/reference/android/content/Context.html#openFileInput%28java.lang.String%29"相对=nofollow>不能包含路径分隔符。
要避免硬编码位置路径,这可能会在原则上,甚至是不同的,从设备到设备,您可以通过调用获取指向存储目录中的文件
对象 getFilesDir
,并用它来阅读你的任何文件喜欢。例如:
To avoid hard-coding the location path, which could in principle even be different from device to device, you can obtain a File
object pointing to the storage directory by calling getFilesDir
, and use it to read whatever file you would like to. For example:
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
请注意,构建一个扫描仪
通过传递字符串
作为一个参数会导致扫描仪工作的内容串,即除preting它作为实际的内容进行扫描,而不是作为打开一个文件的名称。
Note that constructing a Scanner
by passing a String
as a parameter would result in the scanner working on the content of the string, i.e. interpreting it as the actual content to scan instead of as the name of a file to open.
这篇关于Android开放文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!