public class LogFileManager {
public static volatile boolean running = true;
public static Process process;
public static int logFileSize = 4*1024*1024;//4MB
public static InputStream is;
public static FileOutputStream outputStream;
public static void startLog(){
new Thread("UploadLogFile") {
@Override
public void run() {
super.run();
while (running) {
try {
String path = HwContext.getContext().getFilesDir().getPath() + "/"
+ Event.fileName;
Runtime.getRuntime().exec("logcat -c");
String[] cmds = new String[]{"logcat", "*:w"};
File file = new File(path);
process = Runtime.getRuntime().exec(cmds);
is = process.getInputStream();
outputStream = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while (file.length() < logFileSize && (-1 != (len = is.read(buf)))) {
outputStream.write(buf, 0, len);
}
if (file.length() > logFileSize) {
removeLines(file,100);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}.start();
}
public static void stopLog(){
running = false;
process.destroyForcibly();
try {
if (is!=null){
is.close();
}
if (outputStream!=null){
outputStream.close();
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void removeLines(File file, int lineNum) throws IOException{
RandomAccessFile raf = null;
try{
raf = new RandomAccessFile(file, "rw");
long writePosition = raf.getFilePointer();//文件起始位置
for (int i = 0 ; i < lineNum ; i++){
String line = raf.readLine();
if(line == null){
break;
}
}
// Shift the next lines upwards.
long readPosition = raf.getFilePointer();//跳过几行后的位置
byte[] buff = new byte[1024];
int n;
while (-1 != (n = raf.read(buff))) {
raf.seek(writePosition);
raf.write(buff, 0, n);
readPosition += n;
writePosition += n;
raf.seek(readPosition);
}
//raf.setLength(writePosition);
} catch(IOException e){
LogUtils.e(e.toString());
} finally{
try{
if(raf != null){
raf.close();
}
}catch(IOException e){
LogUtils.e(e.toString());
}
}
}
}
java 当文件大于指定的大小后,删除文件前几行继续存储
最新推荐文章于 2022-12-24 10:45:31 发布
该代码段展示了如何在Android中实现日志管理,包括启动日志记录,停止日志记录,以及当日志文件大小超过4MB时删除部分行。使用`logcat`命令收集系统日志,并将其写入文件,同时提供了移除文件顶部行数的功能。
摘要由CSDN通过智能技术生成