I'm creating a Log Filter application that will present a report of all the ERROR entries that were found in the application logs, I was wondering what would be the best method to present a few lines of the stack trace along with each error.
The final result would be something like this:
+ ErrorA
- ErrorB
com.package.Class.method(Class.java:666)
com.package.AnotherClass.ADifferentMethodMethod(Class.java:2012)
com.thatOtherPackage.ThatClass.someOtherMethod(ThatClass.java:34)
+ ErrorC
Here's what I have so far:
public JSONArray processFiles(File[] files){
FileReader fr = null;
BufferedReader br = null;
JSONObject jFiles = new JSONObject();
JSONArray jaf = new JSONArray();
try {
for (File file : files) {
jFiles.put("fileName", file.getName());
boolean fileIsOk = true;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
//Thanks to Windows, there's no way to check file.canRead()
//http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6203387
fileIsOk = false;
}
if(fileIsOk) {
br = new BufferedReader(fr);
String line = null;
JSONObject jLogEntries = new JSONObject();
JSONArray jalog = new JSONArray();
int lineNum = 0;
while ((line = br.readLine()) != null) {
if (line.contains("| ERROR |")) {
jLogEntries.put("line " + lineNum, line);
++lineNum;
}
**// TODO: Implement something to print the next 5 lines of the stack trace.**
}
lineNum = 0;
jalog.add(jLogEntries);
jFiles.put("logEntries", jalog);
jaf.add(jFiles);
}
}// end of files iteration
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return jaf;
}
LineNumberReader is your friend.
LineNumberReadr lr = new LineNumberread(br);
while ((line = lr.readLine()) != null) {
if (line.contains("| ERROR |")) {
jLogEntries.put("line " + lr.getLineNumber(), line);
for (int i = 0; i < 5; i++) {
if ((line = lr.readLine()) != null) {
jLogEntries.put("line " + lr.getLineNumber(), line);
}
}
}
You need to break to the outer loop if there are less then 5 lines in stack, I'll leave it to you to figure that out.
Related
when i run the program the second time my Record.txt gets empty .
i think i'm getting this error in the file reader but i dont know what to do with it.
if you guys can give me a hint i'll appreciate it.
File file = new File("D:\\Program Files\\Oracle\\program\\Record.txt");
if (file.length() <= 0) {
try {
FileReader fr = new FileReader(
"D:\\Program Files\\Oracle\\program\\inventory.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
while ((datas = br.readLine()) != null) {
String[] d = datas.split(",");
int a = Integer.parseInt(d[1]);
int b = Integer.parseInt(d[2]);
items.add(new list(d[0], a, b));
}
br.close();
fr.close();
} catch (IOException | NumberFormatException e) {
System.out.println("Error");
}
}
Iterator itemit = items.iterator();
try {
FileWriter fw = new FileWriter(
"D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedWriter bw = new BufferedWriter(fw);
itemit = items.iterator();
while (itemit.hasNext()) {
list l = (list) itemit.next();
System.out.println(l.ingname + l.qty + l.ingid);
if (item1 == 1 && l.ingid == 100) {
l.qty = l.qty - item1qty;
}
if (item2 == 1 && l.ingid == 200) {
l.qty = l.qty - item2qty;
}
bw.write(l.ingname + ":" + l.qty + ":" + l.ingid);
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException e) {
System.out.println("Error");
}
else{
try{
FileReader fr = new FileReader("D:\\Program Files\\Oracle\\program\\Record.txt");
BufferedReader br = new BufferedReader(fr);
String datas = "";
//System.out.println(file.length());
while((datas = br.readLine()) != null){
String[] d = datas.split(",");
int x = Integer.parseInt(d[1]);
items.add(new list(d[0],x));
}
br.close();
fr.close();
}catch(IOException | NumberFormatException e){
System.out.println("Error");
}
}
From the code parts you provided it looks like the items list is only filled with entries from inventory.txt if the Record.txt file is empty. If it is not empty (f.e. when running the program for a second time) items is probably empty and thus the content of Record.txt will overwritten.
Currently your code looks like this
if (Record.txt file is emtpy) {
read inventory file into items
}
write items to record file
// where is the corresponding if?!
else {
read Record.txt file
}
and is should probably look like this
if (Record.txt file is emtpy) {
read inventory file into items
write items to record file
}
else {
read Record.txt file
}
I've got the file, which can vary in size, in terms of lines. The only thing I know is that it's made of same modules of, lets say, 7 lines. So it means that .txt can be 7, 14, 21, 70, 77 etc. lines. I need to get only header of each module - line 0, 7 and so on.
I've written this code for the job:
textFile = new File(Environment.getExternalStorageDirectory() + "/WorkingDir/" + "modules.txt" );
List<String> headers = new ArrayList<>();
if (textFile.exists()) {
try {
FileInputStream fs= new FileInputStream(textFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fs));
int lines = 0;
int headLine = 0;
while (reader.readLine() != null) { lines++;}
Log.i("Debug", Integer.toString(lines));
while(headLine < lines){
for (int i = 0; i < dateLine - 1; i++)
{
reader.readLine();
Log.i("Debug", reader.readLine());
}
headers.add(reader.readLine());
headLine += 7;
}
Log.i("Debug", headers.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The problem is that it always returns [null]. I do not know where's the problem, since I used similar questions from overflow as references.
ArrayList<String> headerLines = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
int lineCount = 0;
while ((line = br.readLine()) != null) {
// process the line.
if(lineCount % 7 == 0) {
heaaderLines.add(line);
}
lineCount ++;
}
} catch (IOException ioEx) {
ioEx.printStackTrace();
} finally {
br.close();
}
My Java program has a superclass (ProgettoBase) and two underclasses (ProgettoCorpo and ProgettoOre). I must copy two different csv files (progetti_ora.csv and progetti_corpo.csv) to a list but I can't see the elements of the list when I launch the program.
public void readFile () {
List<String> projects = new ArrayList<>();
System.out.println("My list is: " + projects);
//read 1 progetti_ora
String csvFile = "progetti_ora.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
//read 2 progetti_corpo
String csvFileDue = "progetti_corpo.csv";
BufferedReader brDue = null;
String lineDue = "";
String cvsSplitByDue = ";";
//read file 1
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] vote = line.split(cvsSplitBy);
for(String s : vote)
System.out.println("List one: " + s);
for(int x = 0; x <= 2; x++) {
projects.add(vote[x].toString());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("OK1");
//read file 2
try {
brDue = new BufferedReader(new FileReader(csvFileDue));
while ((lineDue = brDue.readLine()) != null) {
String[] voteDue = lineDue.split(cvsSplitByDue);
for(String t : voteDue)
System.out.println("Lista file due: " + t);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("OK2");
}
I want to save to a file in android , Some of my arrayList that will be deleted after that.I already have two methods to write/read from android file here but the problem is I want the two methods do that:
the first method must save the element of arraylist then if I call it again it will not write the new element in the same line but write it in another line
The second must read a line (for example I give to the method which line and it returns what the lines contains)
The file looks like that :
firstelem
secondelem
thridelem
anotherelem
another ..
is this possible to do in android java?
PS: I don't need database.
Update
This is My methods :
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
// stringBuilder.append("\\n");
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Using the save method you linked to you can create the text to save with a StringBuilder:
public String makeArrayListFlatfileString(List<List<String>> listOfLists)
{
StringBuilder sb = new StringBuilder();
if (!listOfLists.isEmpty()) {
// this assumes all lists are the same length
int listLengths = listOfLists.get(0).size();
for (int i=0; i<listLengths; i++)
{
for (List<String> list : listOfLists)
{
sb.append(list.get(i)).append("\n");
}
sb.append("\n"); // blank line after column grouping
}
}
return sb.toString();
}
To parse the contents from that same file (again assuming equal length lists and a String input):
public List<List<String>> getListOfListsFromFlatfile(String data)
{
// split into lines
String[] lines = data.split("\\n");
// first find out how many Lists we'll need
int numberOfLists = 0;
for (String line : lines){
if (line.trim().equals(""))
{
// blank line means new column grouping so stop counting
break;
}
else
{
numberOfLists++;
}
}
// make enough empty lists to hold the info:
List<List<String>> listOfLists = new ArrayList<List<String>>();
for (int i=0; i<numberOfLists; i++)
{
listOfLists.add(new ArrayList<String>());
}
// keep track of which list we should be adding to, and populate the lists
int listTracker = 0;
for (String line : lines)
{
if (line.trim().equals(""))
{
// new block so add next item to the first list again
listTracker = 0;
continue;
}
else
{
listOfLists.get(listTracker).add(line);
listTracker++;
}
}
return listOfLists;
}
For writing, just as Illegal Argument states - append '\n':
void writeToFileWithNewLine(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data + "\n");
outputStreamWriter.close();
}
catch (IOException e) { /* handle exception */ }
}
For reading (just the idea, in practice you should read the file only once):
String readLine(final int lineNo) {
InputStream in = new FileInputStream("file.txt");
ArrayList<String> lines = new ArrayList<String>();
try {
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inReader);
String line;
do {
line = reader.readLine();
lines.add(line);
} while(line != null);
} catch (Exception e) { /* handle exceptions */ }
finally {
in.close();
}
if(lineNo < lines.size() && lineNo >= 0) {
return lines.get(lineNo);
} else {
throw new IndexOutOfBoundsException();
}
}
I'm completely at a lose for why this isn't working. I've had similar loops before and they've worked fine.
try{
text = new BufferedReader(new FileReader(fileName));
while ((lineOfText = text.readLine()) != null){
StringTokenizer tokens = new StringTokenizer(lineOfText," , .;:\"&!?-_\n\t12345678910[]{}()##$%^*/+-");
while (tokens.hasMoreTokens()){
countTotalWordsInDocument++;
String word = tokens.nextToken();
countTotalCharactersInAllWords = countTotalCharactersInAllWords + word.length();
}
}
text.close();
} catch (IOException e) {
System.out.println("file not found");
}