I want to log failed entry in a text file.
}else System.out.println("not found!");
//Enter entry(log it) in a txt file.
How should I go about doing this simply without creating a method?
EDIT:I mean if method is better, then suggestions?
I want to log failed entry in a text file.
}else System.out.println("not found!");
//Enter entry(log it) in a txt file.
How should I go about doing this simply without creating a method?
EDIT:I mean if method is better, then suggestions?
The best thing to do would be to set up a logging framework. You've got JUL, log4j, commons-logging, slf4j, etc. as options. It will take a long time relative to the time I can see you want to spend doing this, but it will be a good investment and it is the "right way to do this". BTW, I recommend slf4j over the others.
That said, you asked for an easy way to do this without creating a method. You can FileUtils.writeStringToFile for this. Here's an example that works the way you want and compiles, you just need to make sure FileUtils is in your classpath:
package com.sandbox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class Sandbox {
public static void main(String[] args) {
try {
FileUtils.writeStringToFile(new File("out.txt"), "not found!", "UTF8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You could use one of the many logging frameworks available, like http://logging.apache.org/log4j/1.2/ for example
If you don't want to download any external logging framework you can use java default logging framework that is in java.util.logging
package package description
To log in a file you have to set a proper handler.
Handler handler = new FileHandler("logHerePath.log", LOG_SIZE, LOG_ROTATION_COUNT);
Logger.getLogger("").addHandler(handler);
If possible in environment etc. you can make a simple Singleton Pattern with a Printwriter that logs the entry.
Then it is only 1 call.
MyLogger.log("my entry\n");