1、初始化目录:
public void init() { logPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "aa"; Log.d(TAG, "logPath : " + logPath); File file = new File(logPath); if (!file.isDirectory()) { boolean make = file.mkdirs(); Log.d(TAG, "make dirs : " + make); } }
2、根据文件名和输出log输出txt文件
public void logToFile(String fileName, String log) { BufferedWriter fw = null; try { String filePath = logPath + File.separator + fileName; File file = new File(filePath); Log.d(TAG, "file path : " + filePath+" , file : "+file.exists()); fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8")); fw.write(log + "\n"); // 写入文件 fw.flush(); // 刷新该流的缓冲 fw.close(); } catch (IOException e) { e.printStackTrace(); Log.d(TAG,"error : "+e); try { if (fw != null) fw.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
3、输出到Bin文件
public void logToFileBin(int index, byte[] log) { String fileStr ="随机数_" + index + ".bin"; DataOutputStream dataOutputStream = null; FileOutputStream outputStream = null; try { String filePath = logPath + File.separator + fileStr; outputStream = new FileOutputStream(filePath); dataOutputStream = new DataOutputStream(new FileOutputStream(filePath)); dataOutputStream.write(log); dataOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); Log.d(TAG,"error : "+e); }finally { try { if (outputStream != null) outputStream.close(); if (dataOutputStream != null) dataOutputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } }使用时,先初始化,创建文件夹,在每次输入文件时,直接调用方法即可!