应用程序未创建文件并抛出FileNotFoundException

时间:2013-10-24 19:30:41

标签: java android io

问题是当我将对话框中的参数发送到mainActivity时。

我通过以下方式发送参数:

mainActivity.SaveInfo(info);

然后转到mainActivity。我的代码如下:

RateDialog.java代码:

public class RateDialog extends DialogFragment {
    public String path;
    public float rate;
    public boolean i;
    PhotosRatingInfo photosRatingInfo;
    PhotosList photosList;

    public RateDialog(String path, float rate, PhotosList photosList) {
        this.path = path;
        this.rate = rate;
        this.photosList = photosList;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
        LayoutInflater inflater = getActivity().getLayoutInflater(); 
        View dialog = inflater.inflate(R.layout.dialog_rate, null);
        final RatingBar ratingBar = (RatingBar)dialog.findViewById(R.id.ratingBar);

        /** Dialog builder and settings **/ 
            builder.setView(dialog)
                    . 
            setTitle("Rate this photo") 
            . 
            setPositiveButton("Rate",new DialogInterface.OnClickListener() {
                @Override
                public void onClick (DialogInterface dialog,int id){
                    rate = ratingBar.getRating();
                    Logic.PhotosRatingInfo info = new Logic.PhotosRatingInfo();
                    MainActivity mainActivity = new MainActivity();
                    info.setRate(rate);
                    info.setPhotopath(path);

                    photosList.list.add(info);
                    ***mainActivity.SaveInfo(info);***
                }
            }

            )
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    }

                    );
            return builder.create();
        }
}

这是mainactivity(下面),这里它给出了错误`“public java.io.FileOutputStream openFileOutput(java.lang.String name,int mode)throws java.io.FileNotFoundException”on:

FileOutputStream stream = openFileOutput(filename, Context.MODE_PRIVATE);`

MainActivity.java的代码:

public class MainActivity extends Activity {
public void SaveInfo(Logic.PhotosRatingInfo info)
{
   save("PhotosData.txt", info)
}
private void save(String filename, Object data)  {
        try {
            FileOutputStream stream = openFileOutput(filename, Context.MODE_PRIVATE);
            ObjectOutputStream os = new ObjectOutputStream(stream);
            os.writeObject(data);
            //stream.write(filename.getBytes());
            os.close();
            stream.close();
        } catch(Exception e) {

        }
    }
}

我对Java的编程有点新意,所以留在我的(:thx for help ...

1 个答案:

答案 0 :(得分:0)

您需要事先创建该文件的目录。

File file = new File("./path/to/file.txt");
if (!file.exists()) {
    file.mkdirs();
}