写入和读取SD卡

时间:2012-03-04 20:13:26

标签: android sd-card writing

我想创建一个每天都会做的事情的应用程序。我已经设法将这一天保存起来,并且在接下来的日子里,我希望它与当天相比。

例: 天= 5; AUX = 5;

明天:

天= 6; AUX = 5;

如果(day!= aux)做某事 否则不做某事

我想将辅助状态保存在Sdcard上的文件中,但很难找到正常工作的代码。我希望有人会看一看并回答它,明天我会需要它。

public class Castle extends Activity {
/** Called when the activity is first created. */

@Override    
public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.castle);


    Calendar calendar = Calendar.getInstance();      
    int day = calendar.get(Calendar.DAY_OF_WEEK);

    int aux=Reading();

    if(day==aux)
    { 
        Intent intent = new Intent(Castle.this, Hug.class);
        startActivity(intent);
    }
    else 
    {
        Intent intent = new Intent(Castle.this, Hug_Accepted.class);
        startActivity(intent);

    try {
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()){
            File file = new File(root, "Tedehlia/state.txt");
            file.mkdir();
            FileWriter filewriter = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(filewriter);
            out.write(day);
            out.close();
        }
    } catch (IOException e) {

    }}




}
public int Reading()
{int aux = 0;
    try{


       File f = new File(Environment.getExternalStorageDirectory()+"/state.txt");

       FileInputStream fileIS = new FileInputStream(f);

       BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));

       String readString = new String();

       if((readString = buf.readLine())!= null){

          aux=Integer.parseInt(readString.toString());


       }

    } catch (FileNotFoundException e) {

       e.printStackTrace();

    } catch (IOException e){

       e.printStackTrace();

    }

    return aux;
} 

}

1 个答案:

答案 0 :(得分:1)

在应用有机会创建文件之前,您似乎正在尝试阅读该文件。我强烈建议您使用SharedPreferences代替SDCard上的文件。

public void onCreate() {
    . . .
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    int aux = prefs.getInt("AUX", -1);
    if (day == aux) {
        . . .
    } else {
        aux = day;
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("AUX", day);
        editor.apply(); // or editor.commit() if API level < 9
    }
    . . .
}