SoFunction
Updated on 2025-03-02

Android development implements file reading and writing

This article shares the specific code for Android file reading and writing for your reference. The specific content is as follows

Read

/**
 * File reading
 * @param is file input stream
 * @return Return to file array
 */
private byte[] read(InputStream is) {
  //Buffer inputStream  BufferedInputStream bis = null;
  // Used to store data  ByteArrayOutputStream baos = null;
  try {
    //Read 1024 each time    byte[] b = new byte[1024];
    //initialization    bis = new BufferedInputStream(is);
    baos = new ByteArrayOutputStream();
    
    int length;
    while ((length = (b)) != -1) {
      //() will add the read data to the b array      //Write the array into baos      (b, 0, length);
    }
    return ();

  } catch (IOException e) {
    ();
  } finally {//Close the flow    try {
      if (bis != null) {
        ();
      }
      if (is != null) {
        ();
      }

      if (baos != null) ();
    } catch (IOException e) {
      ();
    }
  }
  return null;
}

Write

/**
  * Write data to a file
  * @param buffer Write data
  * @param fos file output stream
  */
private void write(byte[] buffer, FileOutputStream fos) {
  //Buffer OutputStream  BufferedOutputStream bos = null;
  try {
    //initialization    bos = new BufferedOutputStream(fos);
    //Write    (buffer);
    //Refresh the buffer    ();
  } catch (IOException e) {
    ();
  } finally {//Close the flow    try {
      if (bos != null) {
        ();
      }
      if (fos != null) {
        ();
      }
    } catch (IOException e) {
      ();
    }
  }
}

use

//Get file input streamInputStream mRaw = getResources().openRawResource();

//Read the filebyte[] bytes = read(mRaw);

//Create a file (the path getFilesDir() is in data/data/<package name>/files, and you need root to see the path)File file = new File(getFilesDir(), "hui.mp3");
boolean newFile = ();

//Writeif (bytes != null) {
 FileOutputStream fos = openFileOutput("hui.mp3", Context.MODE_PRIVATE);
 write(bytes, fos);
}

This step is a time-consuming operation, and it is best to execute it in an io thread

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.