[英]Reading from a raw resource text file
我试图在Android Studio的res \\ raw文件中保留一个.txt文件,并读取/解析该文件。 我在“res”目录中创建了一个名为“raw”的文件夹中的文件“my_file.txt”(我没有创建)。
以下是我认为我的主要问题:创建File对象(与Scanner对象一起使用)时,我应该为我的文本文件传入什么路径?
这是我的代码:
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
}
}
}
认为你正在寻找一些东西
InputStream is = ctx.getResources().openRawResource(res_id);
其中ctx是Context的一个实例
我建议你把它放在src/main
文件夹下的assets
文件夹中。 然后,您可以使用getAssets
方法来检索这样的文件
InputStream in = (Activity)getContext().getAssets().open("my_file.txt")
如果该文件夹不存在,请创建一个: - /
或者您可以使用此功能
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;
}
刚走过路径的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.