Delphian
Delphian

Reputation: 1760

FileNotFoundEception in FileInputStream in android

In my MainActivity class in onResume method I start writeFile method. The class which contains the method:

public class CacheFile {

private static final String TAG = "CacheFile";
private static final String mFileName="cachefile.txt";
private static File file;

//Write data into the file
public static void writeFile(Context context, String data) {
    FileOutputStream outputStream=null;
    String oldData=readFile(context)+"&"+data;
    try {
        file = new File(context.getCacheDir(), mFileName);
        outputStream = new FileOutputStream(file);
        if(data!=null) {
            outputStream.write(oldData.getBytes());
        }
    } catch (IOException e) {
             e.printStackTrace();
    }finally {
        if(outputStream!=null){
            try{
                outputStream.close();
            }catch (Exception e){
               e.printStackTrace();
            }
        }
    }
}

//Read from file
public static String readFile(Context context) {
    BufferedReader inputStream = null;
    FileInputStream fis = null;
    StringBuffer buffer = new StringBuffer();
    String line;

    try {
          file = new File(context.getCacheDir(), mFileName);
          fis=new FileInputStream(file);
          inputStream = new BufferedReader(new InputStreamReader(fis));
          while ((line = inputStream.readLine()) != null) {
            buffer.append(line);
          }
    } catch (IOException e) {
            e.printStackTrace();
    }finally {
        if(inputStream!=null){
            try{
                inputStream.close();
            }catch (Exception e){
                  e.printStackTrace();
            }
        }
        if(fis!=null){
            try{
                fis.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    return buffer.toString();
}


public static void deleteFile(Context context){
  if(file!=null){
     file.delete();
  }
}
}

The first I readFile and add the information for writing but when I try to read file I get FileNotFoundException in line:

fis=new FileInputStream(file) (readfile method). 

Why?

Upvotes: 0

Views: 71

Answers (1)

Eric B.
Eric B.

Reputation: 4702

This means the file really doesn't exist. Do this:

file.createNewFile();
fis = new FileInputStream(file);
// Other code

You can read about createNewFile() here. It only creates the file if it doesn't already exist.

Upvotes: 1

Related Questions