How to write / read integer variable to file from external storage
1 answer
Integer myInteger = Integer.valueOf(10); File file = new File(Environment.getExternalStorageDirectory(), "myfile.dat"); // запись DataOutputStream out = null; try { out = new DataOutputStream(new FileOutputStream(file)); out.writeInt(myInteger.intValue()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } // чтение DataInputStream in = null; try { in = new DataInputStream(new FileInputStream(file)); Integer myReadInt = Integer.valueOf(in.readInt()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } Also needed permishny:
<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> </manifest> Before writing / reading it is better to check the availability of storage:
public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } |