如何在Android Studio中正确访问文本文件
当我尝试读取Android应用程序中的某些文件时,它们似乎不存在,以下是我的代码:如何在Android Studio中正确访问文本文件,android,file,android-studio,Android,File,Android Studio,当我尝试读取Android应用程序中的某些文件时,它们似乎不存在,以下是我的代码: public class ReadFiles1 { //Static Scanner and File Objects static Scanner s; // Static method that returns an ArrayList static ArrayList<String> words (String filename){
public class ReadFiles1 {
//Static Scanner and File Objects
static Scanner s;
// Static method that returns an ArrayList
static ArrayList<String> words (String filename){
//Instantiate File with file name within parameters
File n = new File(filename);
//Instantiate Scanner s with f variable within parameters
//surround with try and catch to see whether the file was read or not
try {
s = new Scanner(n);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Problem here");
}
//Instantiate a new ArrayList of String type
ArrayList<String> theWord = new ArrayList <String>();
//while it has next ..
while(s.hasNext()){
//Initialise str with word read
String str=s.next();
//add to ArrayList
theWord.add(str);
}
//return ArrayList
return theWord;
}
不要将文本文件放在java文件夹中,而是放在
app/src/main/res/raw/
文件夹,并使用下面的代码在程序中读取它
static ArrayList<String> words (InputStream in) {
try {
s = new Scanner(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Problem here");
}
希望这能起作用。在eclipse中运行良好请检查Android Mainfest文件中是否有权限,如果没有添加权限检查文件的完整路径,我认为这是唯一的问题。.这只是意味着没有这样的文件。@ELITE我写了完整路径,但是它不起作用。显示完整路径并添加如何调用
words
方法..我收到错误消息:W/System.err:java.io.FileNotFoundException:/storage/emulated/0/numbers.txt:open failed:enoint(没有这样的文件或目录)我不明白为什么文件不可见,它们在同一个包中,在Eclipse中,我没有任何问题…我只是想澄清一下,txt文件在应用程序中,而不是在外部数据库中,我只是说因为建议。getExternalStorageDirectory()将txt文件放在哪里…如果您可以显示项目结构,那么我可以告诉您原因
static ArrayList<String> words (InputStream in) {
try {
s = new Scanner(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Problem here");
}
InputStream in = getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);
InputStream in = context.getResources().openRawResource(R.raw.numbers);
ArrayList<String> words = ReadFiles1.words(in);