简体   繁体   English

无法在Java中读取文本文件(Android Studio)

[英]Can't read textfile in java (Android studio)

I've tried searching for questions like mine, found alot but non of the answers worked for me. 我尝试搜索像我这样的问题,发现了很多,但是没有答案对我有用。 I'm working with Android studio and trying to open a text file from a java class, but no matter what I do or how I'm trying to open it - I'm getting this error: "... open failed: ENOENT (No such file or directory)" 我正在使用Android Studio,并尝试从Java类中打开文本文件,但是无论我做什么或尝试如何打开它-我都收到此错误:“ ...打开失败:ENOENT (没有相应的文件和目录)”

As you can see - I also tried two options: 1. creating a "File" class (then at the watches window I tried to invoke - "canRead()" function but getting back "false" value. 2. trying to send the ctor of "FileReader" class the path of my file. non of them worked. 如您所见-我还尝试了两种选择:1.创建一个“ File”类(然后在我尝试调用的监视窗口中-“ canRead()”函数但返回“ false”值。2.尝试发送“ FileReader”类的ctor文件路径,没有一个起作用。

thanks alot! 非常感谢!

    public void fillDatabase(){
    File file = new File("C:\\fillStops.txt");

    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DELETE FROM " + STOPS_TABLE_NAME);
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        FileReader fileReader = new FileReader("C:\\fillStops.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            this.addStop(line);
        }
        fileReader.close();
    }
    catch (Exception e){
        String s = e.getMessage();
    }
}

Try this, and place your textfile at the root of your sdcard else change the path for file in the following code. 尝试此操作,然后将文本文件放在sdcard的根目录下,否则在以下代码中更改文件的路径。

File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    String aDataRow = "";

        while ((aDataRow = br.readLine()) != null) {
            line+= aDataRow + "\n";
        }

 Log.d(">>>>>", line);
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

Hop it will clear the things for you. 希望它将为您清除所有问题。 :) :)

PS PS

Don't forget to add the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> permission into your manifest. 不要忘记在清单中添加<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM