简体   繁体   English

正在将文件创建和写入SD卡…“找不到文件”异常即将到来

[英]Creating and Writing a file to the SD card…File Not Found exception is coming

I'm trying to write a file on SD Card but I'm unable to do it. 我正在尝试在SD卡上写入文件,但无法执行。 Can you help me debug the code? 您能帮我调试代码吗?

In the Method WriteToFile at this line it's getting exception FileOutputStream fos = new FileOutputStream(fileWithinMyDir); 在此行的方法WriteToFile ,它获取异常FileOutputStream fos = new FileOutputStream(fileWithinMyDir); .

package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class LauncherFileOperations {

    public void writeToFile(Context context, Object object, String directoryName, String fileName)
    {

    try{
        File mydir = new File(Environment.getExternalStorageDirectory() + directoryName); //Creating an internal dir; 
        if(!mydir.exists())
            mydir.mkdir();

        File fileWithinMyDir = new File(mydir, fileName+".pList"); //Getting a file within the dir. 
        FileOutputStream fos = new FileOutputStream(fileWithinMyDir);

        ObjectOutputStream oos = new ObjectOutputStream(fos); //Select where you wish to save the file...
        oos.writeObject(object); // write the class as an 'object'
        oos.flush(); // flush the stream to insure all of the information was written to 'save.bin'
        oos.close();// close the stream
    }
    catch(Exception ex) {
        Log.v("LauncherFile OPerations.. writeFailed to Launcherfile",ex.toString());
    }
    }

    public Object readFromFile(Context context, String directoryName, String fileName) {
        Object o = null;
        try{
            File mydir = new File(Environment.getExternalStorageDirectory() + directoryName); //Creating an internal dir; 
            File fileWithinMyDir = new File(mydir, fileName+".pList"); //Getting a file within the dir. 
            FileInputStream fis = new FileInputStream(fileWithinMyDir);
            ObjectInputStream ois = new ObjectInputStream(fis);
            o = ois.readObject();
            ois.close();
        }
        catch(Exception ex) {
            Log.v("LauncherFile operations..readFailed ",ex.toString());
        }
        return o;
    }
}
File mydir = new File(Environment.getExternalStorageDirectory() + "/" +directoryName); //Creating an internal dir; 
    if(!mydir.exists())
        mydir.mkdir();

    File fileWithinMyDir = new File(mydir, fileName+".pList"); //Getting a file within the dir. 
    FileOutputStream fos = new FileOutputStream(fileWithinMyDir);

I think you have to give "/" for the folder structure.. And if you have more then one folders please use mkdirs(). 我认为您必须为文件夹结构提供“ /”。如果您有多个文件夹,请使用mkdirs()。

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

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