Realization of File Reading and Writing by android Development

  • 2021-12-05 07:13:52
  • OfStack

In this paper, we share the specific code of android to read and write files for your reference. The specific contents are as follows

Read


/**
*  File reading 
* @param is  Input stream of file 
* @return  Returns an array of files 
*/
private byte[] read(InputStream is) {
  // Buffer inputStream
  BufferedInputStream bis = null;
  // Used to store data 
  ByteArrayOutputStream baos = null;
  try {
    // Every time you read 1024
    byte[] b = new byte[1024];
    // Initialization 
    bis = new BufferedInputStream(is);
    baos = new ByteArrayOutputStream();
    
    int length;
    while ((length = bis.read(b)) != -1) {
      //bis.read() The read data is added to the b Array 
      // Writes an array to the baos Medium 
      baos.write(b, 0, length);
    }
    return baos.toByteArray();

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

      if (baos != null) baos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  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 
    bos.write(buffer);
    // Refresh buffer 
    bos.flush();
  } catch (IOException e) {
    e.printStackTrace();
  } finally {// Close flow 
    try {
      if (bos != null) {
        bos.close();
      }
      if (fos != null) {
        fos.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Use


// Get the file input stream 
InputStream mRaw = getResources().openRawResource(R.raw.core);

// Read a file 
byte[] bytes = read(mRaw);

// Create a file (getFilesDir() The path is in data/data/< Package name >/files, Need root To see the path )
File file = new File(getFilesDir(), "hui.mp3");
boolean newFile = file.createNewFile();

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

This step is a time-consuming operation and is best performed on an io thread


Related articles: