在android 里写个文件保存数据都这么费劲?

创建文件

首先要申请读写SDCard的权限,因为当前已经有一个弹出一个权限,再弹一个当前比较麻烦,当前使用一个简便的方法

android.app.Activity.getExternalFilesDir java code examples | Tabnine

在OnCreate函数里使用

private String mStoreDir;

public void onCreate() {

// 创建文件夹
File externalFilesDir = getExternalFilesDir(null);
if (externalFilesDir != null) {
    mStoreDir = externalFilesDir.getAbsolutePath() + "/screenshots/";
    Log.e(TAG,  mStoreDir);
    File storeDirectory = new File(mStoreDir);
    if (!storeDirectory.exists()) {
        boolean success = storeDirectory.mkdirs();
        if (!success) {
        }
    }
} else {

}
}

在文件夹下创建文件

File saveFile;
saveFile = new File(mStoreDir, "mp-audio-record.pcm");

写文件

private FileOutputStream mFileOutputStream;
try {
  mFileOutputStream = new FileOutputStream(new File(mFileNamePath));
} catch (FileNotFoundException e) {
  mEnd = true;
  SmartLog.e(TAG, "" + e);
}

FileOutputStream只能写入字节流

java FileOutputStream

java FileOutputStream - 简书

当前是要把short 类型写入文件,所以需要先把short 数组转换成 byte数组

byte [] ShortToByte_Twiddle_Method(short [] input)
{
  int short_index, byte_index;
  int iterations = input.length;

  byte [] buffer = new byte[input.length * 2];

  short_index = byte_index = 0;

  for(/*NOP*/; short_index != iterations; /*NOP*/)
  {
    buffer[byte_index]     = (byte) (input[short_index] & 0x00FF); 
    buffer[byte_index + 1] = (byte) ((input[short_index] & 0xFF00) >> 8);

    ++short_index; byte_index += 2;
  }

  return buffer;
}

thread/ handler/ looper 

使用单独的线程去写文件,创建thread, thread对应的Looper,根据Looper去创建handler, 最后向Handler post具体的执行体

private HandlerThread mWorkThread = null;
private Handler mWorkThreadHandler = null;
mWorkThread = new HandlerThread("record-pcm-data");
mWorkThread.start();
mWorkThreadHandler = new Handler(mWorkThread.getLooper());
public void handleNewAudio(final byte[] buffer, final int cntRead) {

  if (mWorkThread != null) {
    final byte[] data = new byte[cntRead];
    System.arraycopy(buffer, 0, data, 0, cntRead);

    mWorkThreadHandler.post(new Runnable() {
      @Override
      public void run() {
        try {
          mFileOutputStream.write(data);
        } catch (IOException e) {
        }
      }
    });
  }
}
  public void endAudio() {
    if (!mEnd && mWorkThread != null) {
      mWorkThreadHandler.post(new Runnable() {
        @Override
        public void run() {
          try {
            mFileOutputStream.close();
            String waveFile = mFileNamePath.replace("pcm", "wav");
            WaveFileUtils.copyWaveFile(mFileNamePath, waveFile, 16000, 16, 1);
          } catch (IOException e) {
          }
          mWorkThread.quitSafely();
        }
      });
    }
  }
}
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐