简体   繁体   中英

Error reading a txt file

I am getting this error in my code when trying to read a file saved on the external storage of my phone :

java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)

I can manage to write data to this file with success, what I did a lot of times. However, I cannot access for reading this same file, giving the entire path or through another method.

The code writing and saving successfully :

File path  = new File(this.getFilesDir().getPath());
            String value = "vegetables";
            // File output = new File(path + File.separator + fileName);
            File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
            try {
                FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
                OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
                outputWriter.write(value);
                outputWriter.close();
                //display file saved message
               // Toast.makeText(getBaseContext(), "File saved successfully!",
                 //       Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
                Log.d("MainActivity", "Chemin fichier = [" + output + "]");
            }
            catch (IOException e) {
                Log.e("Exception", "File write failed: " + e.toString());
            }
        }

The writing piece of code crashing my app :

try
            {
                File gFile;
                FileInputStream fis = new FileInputStream (new File("shopping.txt"));
                //FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
                String line = null, input="";
                while ((line = reader.readLine()) != null)
                    input += line;

                Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
                reader.close();
                fis.close();
                Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
                //return input;
            }
            catch (IOException e)

            {
                Log.e("Exception", "File read failed: " + e.toString());
                //toast("Error loading file: " + ex.getLocalizedMessage());

            }

What am I doing wrong ? For sure, not a problem of permissions, since I can write with success.

Many thanks for your help.

You missed to specifiy the correct path. You are looking for a file named shopping.txt in your current working directory (at runtime). Create a new File object with the correct path and it will work:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt"); . You could reuse your object from writing.

While opening the file, you are simply using new File("shopping.txt") . You need to specify the parent folder, like this:

new File(getExternalFilesDir(),"shopping.txt");

I recommend you make sure of org.apache.commons.io for IO, their FileUtils and FileNameUtils libs are great. ie: FileUtils.writeStringToFile(new File(path), data); Add this to gradle if you wish to use it: implementation 'org.apache.commons:commons-collections4:4.1'

In regards to your problem. When you write your file you are using:

getApplicationContext().getExternalFilesDir(null),"shopping.txt"

But when reading your file you are using:

FileInputStream fis = new FileInputStream (new File("shopping.txt"));

Notice that you didn't specify a path to shopping.txt simply the file name.

Why not do something like this instead:

//Get path to directory of your choice 
public String GetStorageDirectoryPath()
{
    String envPath = Environment.getExternalStorageDirectory().toString();
    String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
    return path;
}

//Concat filename with path
public String GetFilenameFullPath(String fileName){
    return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}

//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);

//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();

BufferedReader br = new BufferedReader(new FileReader(file));
String line;

while ((line = br.readLine()) != null){
      text.append(line);
    if(newLine)
      text.append(System.getProperty("line.separator"));
}
br.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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