当前位置: 代码迷 >> Android >> android 怎么写文件日志到SD卡上.
  详细解决方案

android 怎么写文件日志到SD卡上.

热度:56   发布时间:2016-05-01 19:14:37.0
android 如何写文件日志到SD卡上..

/**
? * 写文件到sd卡上
? *
? * @param context
? */
?public void writeFileToSD(String context) {

//使用RandomAccessFile?写文件?还是蛮好用的..推荐给大家使用...
??String sdStatus = Environment.getExternalStorageState();
??if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
???Log.d("TestFile", "SD card is not avaiable/writeable right now.");
???return;
??}
??try {
???String pathName = "/sdcard/";
???String fileName = "log.txt";
???File path = new File(pathName);
???File file = new File(pathName + fileName);
???if (!path.exists()) {
????Log.d("TestFile", "Create the path:" + pathName);
????path.mkdir();
???}
???if (!file.exists()) {
????Log.d("TestFile", "Create the file:" + fileName);
????file.createNewFile();
???}
???RandomAccessFile raf = new RandomAccessFile(file, "rw");
???raf.seek(file.length());
???raf.write(context.getBytes());
???raf.close();
???//注释的也是写文件..但是每次写入都会把之前的覆盖..
???/*String pathName = "/sdcard/";
???String fileName = "log.txt";
???File path = new File(pathName);
???File file = new File(pathName + fileName);
???if (!path.exists()) {
????Log.d("TestFile", "Create the path:" + pathName);
????path.mkdir();
???}
???if (!file.exists()) {
????Log.d("TestFile", "Create the file:" + fileName);
????file.createNewFile();
???}
???FileOutputStream stream = new FileOutputStream(file);
???String s = context;
???byte[] buf = s.getBytes();
???stream.write(buf);
???stream.close();*/

??} catch (Exception e) {
???Log.e("TestFile", "Error on writeFilToSD.");
??}
?}

  相关解决方案