The java project i have created is to be tested for 1800 cases and the output of each case has to matched with the golden(desired) output. I have created a perl script for this and running it on cygwin.
There are a few cases which throw exceptions but they are wrongly considered to be correct. I want to add a try catch block in java code so that if any exception is thrown it is caught and stack trace is printed on the file exception.txt.
Pseudo Java code:
main()
{
try
{
... //complete code of main()
}
catch (Exception e)
{
FileWriter fstream=new FileWriter("exception.txt");
BufferedWriter out=new BufferedWriter(fstream);
out.write(e.toString());
out.close();
}
}
But this overwrites the previous file contents and finally file contains the last thrown exception. How can i write catch block so that stackTrace is printed and contents of file are intact and not overwritten each time.
Use this constructor instead:
new FileWriter ("exception.txt", true);
It is described here.
EDIT: As per Jon's comment below:
If you want to print the entire stack trace, use printStackTrace:
fw = new FileWriter ("exception.txt", true);
pw = new PrintWriter (fw);
e.printStackTrace (pw);
Also, use the appropriate close calls after that.
You can use:
FileOutputStream fos = new FileOutputStream(new File("exception.txt"), true);
PrintStream ps = new PrintStream(fos);
e.printstacktrace(ps);
Here is a program that demonstrates what I think you need:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class StrackTraceAppender {
public static void main(String[] args) {
try {
thrower("Oh noes!");
} catch (Exception e) {
appendToFile(e);
}
try {
thrower("I died!");
} catch (Exception e) {
appendToFile(e);
}
}
public static void thrower(String message) throws Exception {
throw new RuntimeException(message);
}
public static void appendToFile(Exception e) {
try {
FileWriter fstream = new FileWriter("exception.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
PrintWriter pWriter = new PrintWriter(out, true);
e.printStackTrace(pWriter);
}
catch (Exception ie) {
throw new RuntimeException("Could not write Exception to file", ie);
}
}
}
It uses the printStackTrace(PrintWriter) method on Throwable to print the entire stack trace to the end of a file called "exception.txt", then there's a main() method which demonstrates usage with two sample exceptions. If you run it in your IDE, you should find that you get a file with two stack traces written to it (works for me).
Use
FileWriter fstream=new FileWriter("exception.txt", true);
to create an appending file writer.
Try this:
PrintStream printStream = new PrintStream(new File("exception.txt"));
try {
//error proven code
} catch (Exception exception) {
exception.printStackTrace(printStream);
}
Try this:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class ErrorLogger
{
private Logger logger;
public ErrorLogger()
{
logger = Logger.getAnonymousLogger();
configure();
}
private void configure()
{
try
{
String logsFolder = "logs";
Files.createDirectories(Paths.get(logsFolder));
FileHandler fileHandler = new FileHandler(logsFolder + File.separator + getCurrentTimeString() + ".log");
logger.addHandler(fileHandler);
SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
} catch (IOException exception)
{
exception.printStackTrace();
}
addCloseHandlersShutdownHook();
}
private void addCloseHandlersShutdownHook()
{
Runtime.getRuntime().addShutdownHook(new Thread(() ->
{
// Close all handlers to get rid of empty .LCK files
for (Handler handler : logger.getHandlers())
{
handler.close();
}
}));
}
private String getCurrentTimeString()
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
return dateFormat.format(new Date());
}
public void log(Exception exception)
{
logger.log(Level.SEVERE, "", exception);
}
}
Usage:
ErrorLogger errorLogger = new ErrorLogger();
try
{
throw new Exception("I died!");
} catch (Exception exception)
{
errorLogger.log(exception);
}
Related
So I'm trying to write in a text file, nothing too complicated, but for some reason the new text that i want to add doesn't change lines, it keeps going on the same line, and I can't figure out why. The irrelevant parts are being commented so don't worry about them.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
public static void main( String args[]) {
int a = 32;
int b=12;
int c=33;
List<Integer> myList = new ArrayList();
myList.add(a);
myList.add(b);
myList.add(c);
/* for(int s:myList)
{
System.out.println(s);
}
*/
//Om ar= new Om("Alex",21,185);
//System.out.println(ar);
try{
File myObj = new File("filename.txt");
if(myObj.createNewFile()){
System.out.println("File created " + myObj.getName());
}
else
{
System.out.println("File already exists");
}
}
catch (IOException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
try {
FileWriter myWriter = new FileWriter("filename.txt");
for(int i=1;i<10;i++)
{
myWriter.append("This is a new file, nothing sus here."+i + " ");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Wrap your FileWriter in a BufferedWriter to make writing to the file more efficient.
Then you can use the newLine() method of the BufferedWriter to add a newline String to the file as you require. The newLine() method will write out the appropriate string for your current platform.
While running my java file io program I'm getting FileNotFoundException
I tried changing the directory of the file and most of the other solution mentioned in SO, nothing works.
My code:
package com.HelloWorld;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
FileWriter w=null;
BufferedWriter bw=null;
try {
String s="welcome";
String b="D:\\test.txt";
w=new FileWriter(b);
bw=new BufferedWriter(w);
bw.write(s);
bw.flush();
}
catch(IOException e)
{
System.out.println("exception caught"+e);
}
finally{
try {
if(bw!=null)
bw.close();}
catch(Exception e) {
System.out.println("exception caught"+e);
}
try {
if(w!=null)
{
w.close();
System.out.println("success");
}}
catch(Exception e) {
System.out.println("exception caught"+e);
}
}
}
}
I had already created the file in the D drive so the FileWriter overrides the already created file name because of which it did not write to the file
It's been a while since I've used Java so I feel silly that this is confusing me, but I have a class 'FileProcessor' in a 'FileProcessor.java' file. I'm trying to use it in my 'Driver.java' file but I keep getting this error:
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
I'm a little confused by the whole exceptions thing in Java and I thought I handled it in my FileProcessor.java file but I don't know.
FileProcessor.java
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class FileProcessor{
/**
* Reads one line from file
* #param arg A file
* #return The line that is read
*/
public String readLineFromFile(File f) throws FileNotFoundException,
IOException{
BufferedReader br = null;
String line;
try{
br = new BufferedReader(new FileReader(f));
line = br.readLine();
return line;
}
catch(IOException e){
e.printStackTrace();
System.err.println("Read method failed");
throw new IOException();
}
catch(FileNotFoundException e1){
e1.getMessage();
System.err.println("File is not found");
throw new FileNotFoundException();
}
}
}
Driver.java
import java.io.File;
import java.io.FileNotFoundException;
public class Driver{
public static void main(String args[]){
File inFile = null;
if (0 < args.length){
inFile = new File(args[0]);
}
else{
System.err.println("No input file found");
System.exit(0);
}
FileProcessor fileProcessor = new FileProcessor();
String lineRead;
try{
lineRead = fileProcessor.readLineFromFile(inFile);
}
catch(FileNotFoundException e){
throw new FileNotFoundException();
}
}
}
Your main throws a new FileNotFoundException in the catch block which can't be catched outside of main. Change:
import java.io.File;
import java.io.FileNotFoundException;
public class Driver{
public static void main(String args[]){
File inFile = null;
if (0 < args.length){
inFile = new File(args[0]);
}
else{
System.err.println("No input file found");
System.exit(0);
}
FileProcessor fileProcessor = new FileProcessor();
String lineRead;
try{
lineRead = fileProcessor.readLineFromFile(inFile);
}
catch(FileNotFoundException e){
System.out.print(e.getMessage());
}
}
}
Throwing a new IO- or FileNotFoundException when you catch them is not a good handling of this exceptions.
catch(IOException e){
e.printStackTrace();
System.err.println("Read method failed");
throw new IOException();
}
First, you loose the Exception information (which file can not be found, what exactly happened, ...). Second, it does not really catch them if you throw it again, so you have to catch them again one frame above.
So, the simplest possible solution is to delete the throw statement.
public class FileProcessor{
public String readLineFromFile(File f)
// this can be deleted if you catch the exceptions
// in here (and do not rethrow them)
// throws FileNotFoundException, IOException
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
return br.readLine();
} catch(IOException e) {
e.printStackTrace();
// throw new IOException();
}
// this can be deleted because FileNotFoundException is a
// subclass of IOException and is caught above
// catch(FileNotFoundException e1){
// e1.getMessage();
// System.err.println("File is not found");
// throw new FileNotFoundException();
// }
// and after all, you should close the BufferedReader
// or use the "try-with-resources"
finally {
if(br != null) { br.close(); }
}
}
}
There are few things to do with Exceptions.
You catch the Exception and you write your appropriate code needed to handle the Exception, Example logging, setting error message or triggering fail mail, retry with new file name etc. For this you write the catch block along with try.
2.You catch the Exception and you write your appropriate code needed to handle the Exception, Example logging etc but you want future code which calls your method to catch and process the exception again. In this case you will re throw the exception using throw new and add it in throws. you can even throw new Exception type like
catch(NullPointerException e) {
throw new RecipeNotFoundException("No recipe found");
}
Delay the handling to future code which calls this method. This is done by writing throws clause. Throws tell method(s) calling a method that there are possibilities an exception can occur here and it is not caught and you need to catch and you wont write catch.
In your code you have caught the code in FileProcessor.readLineFromFile(File) method but you have also added throws clause to the method. So the system thinks there are chances an exception can be re thrown and not caught possible another FileNotFoundException from the catch block.
One more thing after catching the Exception you have re thrown same exception throw new IOException(); and throw new FileNotFoundException(); remove that too.
If you go through Java documentation on FileNotFoundException and IOException here. docs.oracle.com/javase/7/docs/api/java/io/… and docs.oracle.com/javase/7/docs/api/java/io/IOException.html you will notice FileNotFoundException actually extends IOException so you do not have to actually catch FileNotFoundException.
I've found answers to various questions on here before, but this is my first time asking one. I'm kicking around an idea for my final project in my computer programming class, and I'm working on a few proof of concept programs in Java, working in Eclipse. I don't need anything more than to get the filepaths of the contents of a directory and write them to a .txt file. Thanks in advance!
Edit: I am posting my code below. I found a snippet of code to use for getting the contents and print them to the screen, but the print command is a placeholder that I'll replace with a write to folder command when I can.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ScanFolder {
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
}
EDIT: I've enclosed the OutputStreamWriter in a BufferedWriter
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("txt.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
writeContentsOfFileToAFile(new File("."), out, true); // change true to
// false if you
// don't want to
// recursively
// list the
// files
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void writeContentsOfFileToAFile(File parent, BufferedWriter out, boolean enterIntoDirectory) {
for (File file : parent.listFiles()) {
try {
out.write(file.toString() + "\r\n");
} catch (IOException e) {
e.printStackTrace();
}
if (enterIntoDirectory && file.isDirectory())
writeContentsOfFileToAFile(file, out, enterIntoDirectory);
}
}
Is this what you need?
I'm trying to read ObjectOutputStream from a file and convert it to an arraylist.
This whole thing is happening inside a method which should read the file and return the array list:
public static List<Building> readFromDatabase(){
String fileName="database.txt";
FileInputStream fileIStream=null;
ObjectInputStream in=null;
List<Building> buildingsArr=null;
try
{
fileIStream = new FileInputStream(fileName);
in = new ObjectInputStream(fileIStream);
buildingsArr=(ArrayList<Building>)in.readObject();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
return buildingsArr;
}
}
Java tells me that this is dangerous.
What are the alternatives?
I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.
I need to both make sure files will be closed, and return the array list I created as well.
Any ideas?
I can't put the return in the "try" block because it won't do it / it
won't close files in the "finally" block.
Wrong, finally block would still execute if you put return in try block. Thus you can return in your try block.
try
{
//your code
return buildingsArr;
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
}
I would suggest starting to use Java 7, and the try with resources clause. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ex:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
You must either throw an Exception or return a value:
All you need to prove this is comment out the return "File Not Found" after the finally block and see that it won't compile.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReturnFinallyExample
{
public static void main(final String[] args)
{
returnFinally();
}
private static String returnFinally()
{
try
{
final File f = new File("that_does_not_exist!");
final FileInputStream fis = new FileInputStream(f);
return "File Found!";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally!");
}
return "File Not Found!";
}
}
You must have the return after the finally or you have to either:
declare the method to throws FileNotFoundExceptoin and re-throw the FileNotException out.
or
wrap the FileNotFoundException with throw new RuntimeException(e)