Android Studio中加载文件 [英] Load file in Android Studio
问题描述
我曾尝试解决这里建议:
装载Android Studio中一个简单的文本文件
等等。
I have tried the solution suggested here: Load a simple text file in Android Studio among others.
我需要将文件从活动类的外部加载,和值在不同的其他类使用。
I need to load the files from outside of an activity class, and the values be used in various other classes.
(旁注我不一定要拥有资产文件夹中的文件,他们可以在任何地方,只要我能以某种方式加载它们)。
(Sidenote I don't necessarily have to have the files in the assets folder, they can be anywhere, as long as I could somehow load them).
基本上,它告诉我要检查一个名为app.iml文件中有这样一行:
Basically, it tells me to check a file named "app.iml" to have this line:
option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets"
它呢。
在此之后,将文件添加到资产目录。
After that, add the files to the "assets" directory.
我然后尝试将文件加载有:
I then try to load the file with:
File file = new File("IDs.txt");
和
Scanner in = new Scanner(file);
但我得到一个文件未发现异常。
But I get a File Not Found exception.
无论身在何处,我把这些文件,我不能够加载它们。
有什么建议?
No matter where I put the files, I am not able to load them. Any suggestions?
推荐答案
答复制与文件夹的应用程序更新
Answer updated with copying file to app folder
您不能从资产打开的文件与文件f =新的文件。你应该打开的资产是这样的:
You cant open file from assets with File f = new File. You should open assets like this:
File ids = new File(getExternalFilesDir("txt") + File.separator + "IDs.txt");
InputStream is = null;
if (!ids.exists()) {
AssetManager manager = getAssets();
try {
is = manager.open("IDs.txt");
} catch (IOException e) {
e.printStackTrace();
}
if (is != null)
try{
OutputStream outputStream = new FileOutputStream(ids);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
现在你可以设置文件或FILE_PATH你等级:
Now you can set file or file_path to you class:
File ids = new File(getExternalFilesDir("txt") + File.separator + "IDs.txt");
要得到一个完整的路径中使用 ids.getAbsolutePath();
To get a full path use ids.getAbsolutePath();
这篇关于Android Studio中加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!