什么样的android不妥openFileOutput?不妥、android、openFileOutput

2023-09-12 02:21:50 作者:万劫不复

我试着用openFileOutput功能,但它不希望编译...犯规承认德功能。即时通讯使用Android SDK中1.6。这是一个SDK的问题?这是一个参数问题?

 进口java.io.FileOutputStream中;
公共静态无效保存(字符串文件名,MyObjectClassArray [] theObjectAr){
        FileOutputStream中FOS;
        尝试 {
            FOS = openFileOutput(文件名,Context.MODE_PRIVATE);


            ObjectOutputStream的OOS =新的ObjectOutputStream(FOS);
            oos.writeObject(theObjectAr);
            oos.close();
        }赶上(FileNotFoundException异常E){
            e.printStackTrace();
        }赶上(IOException异常E){
            e.printStackTrace();
        }
    }
 

解决方案

您的方法应该如下。需要一个额外的上下文作为参数。这种方法,你可以通过你的服务或活动

 公共静态无效保存(字符串文件名,MyObjectClassArray [] theObjectAr,
  上下文CTX){
        FileOutputStream中FOS;
        尝试 {
            FOS = ctx.openFileOutput(文件名,Context.MODE_PRIVATE);


            ObjectOutputStream的OOS =新的ObjectOutputStream(FOS);
            oos.writeObject(theObjectAr);
            oos.close();
        }赶上(FileNotFoundException异常E){
            e.printStackTrace();
        }赶上(IOException异常E){
            e.printStackTrace();
        }
    }
 
安卓学习笔记

Im trying to use openFileOutput function but it doesnt want to compile... doesnt recognize de function. Im using android sdk 1.6. Is this a sdk problem ? Is this a parameter problem ?

import java.io.FileOutputStream;
public static void save(String filename, MyObjectClassArray[] theObjectAr) {
        FileOutputStream fos;
        try {
            fos = openFileOutput(filename, Context.MODE_PRIVATE);


            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(theObjectAr); 
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

解决方案

Your method should be as follows. Takes in an extra Context as a parameter. To this method you can pass your Service or Activity

public static void save(String filename, MyObjectClassArray[] theObjectAr, 
  Context ctx) {
        FileOutputStream fos;
        try {
            fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);


            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(theObjectAr); 
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }