How to record/read integer in the file - android



  • How to record/read variable integer in a file from external storage



  • 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();
            }
        }
    }
    

    Permits are also required:

    <manifest ...>
    
    &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt;
    &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;
    

    </manifest>

    Before recording/reference, it is better to check the availability of the vault:

    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;
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2