package com.cv.java.log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import org.apache.log4j.Logger;
/**
* @author Chandra Vardhan
*/
public class ReadLogFile {
private static final Logger LOGGER = Logger.getLogger(ReadLogFile.class);
static URL url = null;
static {
url = readLogFile();
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
String inputFile = url.getFile();
String output = "c:/cv/extracted.log";
ensureDirFileAvailable(new File(output));
System.out.println(buildFile(inputFile, output));
}
private static String buildFile(final String input, final String output) {
BufferedReader in = null;
StringBuffer sb = null;
try {
in = new BufferedReader(new FileReader(input));
sb = readLines(in);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileOutputStream fop = null;
try {
File file = new File(output);
fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
fop.write(sb.toString().getBytes());
fop.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
private static StringBuffer readLines(final BufferedReader in) {
StringBuffer sb = new StringBuffer();
String line = "";
if (in != null) {
try {
while ((line = in.readLine()) != null) {
if (line != null) {
line = line.trim();
if (line.contains("ERROR") || line.contains("Exception")) {
sb.append(line).append("\n").append("**********#######****************########**********")
.append("\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb;
}
private static URL readLogFile() {
URL url = null;
try {
LOGGER.info("Reading properties file : app_log.log!!!");
url = ReadLogFile.class.getClassLoader().getResource("app_log.log");
} catch (Exception e) {
LOGGER.error("Problem while reading properties file!!!");
}
return url;
}
private static File ensureDirFileAvailable(final File file) {
File result = file;
try {
if (result == null) {
result = provideDummyFile();
}
if (result != null) {
if (result.isFile() || !result.exists()) {
File parentFile = result.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
result.createNewFile();
}
}
} catch (Exception e) {
System.err.println("Problem while accessing the file path : : " + result);
e.printStackTrace();
}
return result;
}
private static File provideDummyFile() {
return new File("C:/cv/test.txt");
}
} |
No comments:
Post a Comment