[英]Reading from a raw resource text file
I'm trying to keep a .txt file in my res\\raw file in Android Studio and read/parse the file. 我试图在Android Studio的res \\ raw文件中保留一个.txt文件,并读取/解析该文件。 I have a file "my_file.txt" in a folder called "raw" that I created in the "res" directory (that I didn't create).
我在“res”目录中创建了一个名为“raw”的文件夹中的文件“my_file.txt”(我没有创建)。
Here's what I think my main issue is: When creating the File object (to use with the Scanner object), what path should I pass in for my text file? 以下是我认为我的主要问题:创建File对象(与Scanner对象一起使用)时,我应该为我的文本文件传入什么路径?
Here's my code: 这是我的代码:
private void readFile(){
Scanner scanner = null;
try {
scanner = new Scanner(new File("\\res\\raw\\my_file.txt")); //I've also tried without the .txt extension
Log.v("readFile->try","Trying to read file.");
}catch(Exception e)
{
//Send error message.
}
if(scanner != null) {
while (scanner.hasNext()) {
String[] line = scanner.nextLine().split("\t");
//Process string here
}
}
}
Think you are looking for something along the lines of 认为你正在寻找一些东西
InputStream is = ctx.getResources().openRawResource(res_id);
Where ctx is a instance of Context 其中ctx是Context的一个实例
I suggest you put it in assets
folder under the src/main
folder. 我建议你把它放在
src/main
文件夹下的assets
文件夹中。 Then you can use the getAssets
method to retrieve the file like this 然后,您可以使用
getAssets
方法来检索这样的文件
InputStream in = (Activity)getContext().getAssets().open("my_file.txt")
If the folder does not exists, create one :-/ 如果该文件夹不存在,请创建一个: - /
or You can use this Function 或者您可以使用此功能
private String readFile()
{
String myData = "";
File myExternalFile = new File("assets/","log.txt");
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine + "\n";
}
br.close();
in.close();
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
return myData;
}
just past in the path Location. 刚走过路径的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.