Android日志文件读写 Android日志文件的读写工具类
法迪 人气:01. UI 效果
例如我们需要采集温度信息,可以不断写入一行一行的txt文本,读写文件操作即可
2. 调用示例
2.1 需要配置SD卡读写权限
<uses-sdk android:minSdkVersion="17" android:targetSdkVersion="17" /> <!-- 往sdcard中写入数据的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 在sdcard中创建/删除文件的权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
2.2 调用
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for (int i = 0; i < 100; i++) { FileSaveUtil.writeFile("Temperature01.txt", String.format("Temperature : %.1f 摄氏度" , 30 + (float) i % 10)); } } }
3.工具类源码
package com.wu.sufadi; import java.io.File; import java.io.RandomAccessFile; import android.os.Environment; public class FileSaveUtil { public final static String FILE_PATH = Environment.getExternalStorageDirectory() + "/PhoneData/"; public static void writeFile(String fileName, String content) { String strContent = content + "\n"; try { File fileDir = new File(FILE_PATH); if (!fileDir.exists()) { fileDir.mkdirs(); if (!fileDir.exists()) { return; } } File file = new File(FILE_PATH, fileName); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(file.length()); raf.write(strContent.getBytes()); raf.close(); } catch (Exception e) { e.printStackTrace(); } } public static void delLogFile(String path) { File file = new File(path); if (file.exists()) { file.delete(); } } }
加载全部内容