Skip to content

Instantly share code, notes, and snippets.

@fangzhzh
Last active July 21, 2016 02:36
Show Gist options
  • Save fangzhzh/6ec280eeddea079a3770a4f8e66d7537 to your computer and use it in GitHub Desktop.
Save fangzhzh/6ec280eeddea079a3770a4f8e66d7537 to your computer and use it in GitHub Desktop.
Java read and wait file, BufferedReader, also ffmpeg progress calculation, try catch, finally, FileReader
BufferedReader br = null;
try {
br = new BufferedReader(
new FileReader(output.getAbsolutePath() + ".log"));
String line;
double totalSecs = 0;
double totalFps = 0;
while (keepReading) {
line = br.readLine();
if (line == null) {
//wait until there is more of the file for us to read
Thread.sleep(1);
} else {
Pattern durPattern = Pattern.compile("(?<=Duration: )[^,]*");
Scanner sc = new Scanner(line);
String dur = sc.findWithinHorizon(durPattern, 0);
if (totalSecs <= 0 && TextUtils.isEmpty(dur)) {
continue;
}
if (totalSecs <= 0 && !TextUtils.isEmpty(dur)) {
String[] hms = dur.split(":");
totalSecs = Integer.parseInt(hms[0]) * 3600 + Integer.parseInt(hms[1]) * 60 + Double.parseDouble(hms[2]);
System.out.println("Total duration: " + totalSecs + " seconds.");
continue;
}
Pattern fpsPattern = Pattern.compile("[0-9.]* (?=fps)");
String fps = sc.findWithinHorizon(fpsPattern, 0);
if (totalFps <= 0 && TextUtils.isEmpty(fps)) {
continue;
}
if (totalFps <= 0 && !TextUtils.isEmpty(fps)) {
totalFps = Double.valueOf(fps) * totalSecs;
System.out.println("Total fps: " + totalFps + " fps.");
continue;
}
Pattern framePatter = Pattern.compile("(?<=frame=)[0-9 ]*");
String frame = sc.findWithinHorizon(framePatter, 0);
if (!TextUtils.isEmpty(frame)) {
double progress = Double.valueOf(frame) / totalFps;
System.out.printf("Progress: %.2f%%%n", progress * 100);
continue;
}
Pattern finishPattern = Pattern.compile("successfully");
String finish = sc.findWithinHorizon(finishPattern, 0);
if (!TextUtils.isEmpty(finish)) {
System.out.printf("Progress: 100%%");
br.close();
break;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException io) {
//log exception here
}
try {
File file = new File(output.getAbsolutePath() + ".log");
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment