【问题标题】:FileNotFoundEception in FileInputStream in androidandroid中FileInputStream中的FileNotFoundException
【发布时间】:2016-06-15 08:07:06
【问题描述】:

在 onResume 方法的 MainActivity 类中,我启动 writeFile 方法。包含该方法的类:

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();
  }
}
}

首先我读取文件并添加写入信息,但是当我尝试读取文件时,我得到 FileNotFoundException 行:

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

为什么?

【问题讨论】:

    标签: android file-io filenotfoundexception


    【解决方案1】:

    这意味着该文件确实不存在。这样做:

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

    您可以阅读有关createNewFile() here 的信息。它只会在文件不存在时创建文件。

    【讨论】:

    • 是的,谢谢它的工作。我应该将 createNewFile 方法添加到 writeFile 方法吗?或者在readFile方法中添加就足够了。
    • 不需要,因为在writeFile()中,第一个被调用的方法是readFile()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多