Im trying to create a log file for a small chatroom I've created.
so far this is what I have for the logging:
static void log(String s){
try{
BufferedWriter writer =
new BufferedWriter(new FileWriter("log"+getTime()+".txt"));
writer.write(s);
}catch(IOException e){
e.printStackTrace();
}
}
I call it in this way in a thread for each connection each time I brodcast to the clients:
log(name+"String")
but after its called and doesn't continue the program. however, when this did work, the only thing in the text file would be one line, the first one called. how can one fix both these bugs?
As stated in the other answers, you don't close the file and you are not writing a line separator.
I see that there's one perfect answer in Java 7, but you said in the comments that you are not able to use that. (I suppose you are using Java 6 instead)
Because of that, I have written an implementation using only Java 6 API (using the Java 6 javadocs for reference):
public class LogFileHelper {
private final BufferedWriter writer;
public LogFileHelper(File outputFile) throws IOException {
if(!outputFile.exists()){ //The JavaDoc says that it is not certain if the file will be created
outputFile.createNewFile();
}
this.writer = new BufferedWriter(new FileWriter(outputFile, true));
}
public void writeLine(String line) throws IOException {
if(line == null){
throw new IllegalArgumentException("line may not be null");
}
this.writer.write(line);
this.writer.newLine();
this.writer.flush(); //Make sure the line we just wrote is written and kept if the application crashes
}
public void tryWriteLine(String line) {
try {
writeLine(line);
} catch(IOException ioe){
//Your exception handling here
}
}
public void close() throws IOException {
this.writer.close();
}
public void tryClose() {
try {
this.writer.close();
} catch(IOException ioe){
//Your exception handling here
}
}
}
I added tryXXX methods to simplify exception handling, as I suppose you will use the same everywhere. I kept the base methods to allow for custom exception handling where needed.
With above class, you would store the instance somewhere, write to it where needed and close it on exit. Your best bet for that is a shutdown handler like this one:
Runtime.getRuntime().addShutdownHook(new Thread("Chatlog Shutdown Thread"){
#Override
public void run(){
myLogFileHelper.tryClose();
}
});
Where you would execute that statement just after you create your LogFileHelper instance.
The above code does flush every time you write something - If you want to go super efficient, you could flush less often. A valid use case for not flushing immediately would be when writing a whole batch of lines at once, although you always have to balance between not flushing and having the file on disk immediately.
Use try-with-resources and write in append mode:
static void log(String s) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("log" + getTime() + ".txt", true)))) {
out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
You have several problems:
each time you log one statement you open a new file descriptor;
... which you don't close;
given on the output of .getTime() you may even write to several different files.
Use a dedicated class which you initialize and share once across all classes which use logging facilities; for instance a singleton.
In the constructor you would open the file:
private final BufferedWriter writer;
// ...
public MyLogFile()
throws IOException
{
final Path path = Paths.get("path to logfile");
writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
Use a method to write a line:
public void writeOneLine(#Nonnull final String line)
throws IOException
{
Objects.requireNonNull(line, "won't write null, sorry");
writer.write(line);
writer.newLine();
writer.flush();
}
As for closing the file when you exit, either make you class implement Closeable and .close() it when your program ends (or even AutoCloseable) or add a JVM shutdown hook.
Related
I wanted to write to a property file. But it silently never worked. Just from the code behavior I could not notice it. I always had to open the properties file and look if the value changed. But it never did. So actually I would expect to get an exception . The problem seemed to be that I did not close the InputStream before opening the OutputStream. But I never got to know that. It cost me 3 days because I would expect either OutputStream or store function to give me some feedback. Have a look at the code.
File file = ResourceUtils.getFile("classpath:First.properties");
FileInputStream in = new FileInputStream(file);
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("country"));
in.close(); // This I always forgot
FileOutputStream out = new FileOutputStream(file);
props.setProperty("country", "germany");
props.store(out, null);
System.out.println(props.getProperty("country"));
out.close();
As for the actual question "why does it not throw an exception", it's because there are cases you want the Stream to remain open.
class FileWriteSample implements Closeable {
FileOutputStream writeTo;
public FileWriteSample(String filename) throws IOException {
writeTo = new FileOutputStream(filename);
// should we expect an Exception here because we don't close the Stream?
// we're planning to use it later on
}
public void write(String s) {
// write to stream
}
public void close() throws IOException {
writeTo.close();
}
}
A forgotten close() statement cannot cause an exception. From the perspective of your stream everything is okay. It just didn't wrote to its destination yet. Why should it? Even when the whole program terminates there is no guaranty that the stream closes and writes its internal buffers out.[1]
You always have to call flush() or close() actively. The underlying implementation will then perform the actual write operation.
This mistake is so common that there is an extra Java-Feature to handle it. It is called try-with-resources and prevents programmers from the evil consequences of missing close() statements.
Example:
//use try-with-resources on out
private void saveProperties(Properties properties, String path) {
try(PrintStream out = new PrintStream(new FileOutputStream(path))) {
printProperties(properties,out);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// you can pass System.out as well to print to console
private void printProperties(Properties properties, PrintStream out) {
try {
properties.store(out, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//properties.load leaves the stream open, so you have to use try-with-resources
private Properties readProperties(String path) {
try (FileInputStream in = new FileInputStream(path)) {
Properties properties = new Properties();
properties.load(in);
return properties;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Related posts on Java Properties:
Read properties from outside of a jar: https://stackoverflow.com/a/54766296/1485527
Sorted print of properties: https://stackoverflow.com/a/54781548/1485527
Related posts on Java Streams:
Closing Streams in Java
[1] See: Josh Bloch, Effective Java,(2nd ed.), Page 27.
Avoid finalizers.[...] It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable.
I have a Java program littered with values I want to log to a txt file. I'm new to the language and finding it not so straight forward.
I created a Logger class:
public static void loggerMain(String content) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("debug.txt", true)));
out.println(content);
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
I then call the method in another class:
Logger.loggerMain("testing");
It logs the String but if I then run the script again, it will append the same String to a new line.But I don't want the same println to be appended each time the script is called. I want to override the file. How would I go about this?
If I change the FileWriter argument to False, the file will only log the latest call to the method. e.g.:
Logger.loggerMain("testing1");
Logger.loggerMain("testing2");
Only Logger.loggerMain("testing2"); will be logged. I know why, it's because I'm creating a new file each time I call the method.. but I really don't know the solution to this!
If I understood you correctly you want to clear the log for every time the programm is executed. You can do this with the following addition to the Logger class:
class Logger {
private static boolean FIRST_CALL = true;
public static void loggerMain(String content) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("debug.txt", !FIRST_CALL)));
if(FIRST_CALL){
FIRST_CALL = false;
}
out.println(content);
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
}
With the variable FIRST_CALL we track if the logger has been executed for the first time in the current script context. If it is, we overwrite the file, by passing in false (!FIRST_CALL) into the FileWriter
Just a re-iteration of the other answer:
class Logger {
private static boolean FIRST_CALL = true;
public static void loggerMain(String content) {
try (
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("debug.txt", !FIRST_CALL)))) {
FIRST_CALL = false;
out.println(content);
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
}
try-with-resources will spare you an explicit close() call, and will properly close the resource regardless of completing the block normally or with an exception.
This one is subjective: as the code will touch FIRST_CALL anyway, I feel it simpler to set it without the extra check.
I have this code but there is an error to this,
I am not good with java so I posted my problem in here... this is my code
public static void SaveFile() throws IOException{
System.out.println("Saving File!");
FileWriter toTextFile = new FileWriter("output.txt");
for(x=0;x<new_num_book;x++){
toTextFile.write(name[x]);
}
toTextFile.close();
}
blah blah
else if(option == 5){
SaveFile();
}
the problem is that netbeans declares an error in accessing the SaveFile function. Please help! Thanks
saveFile throws an IOException, you need to handle it or pass it on to the caller.
Take a look at The try Block for more details
Without more context it's hard to say what you should do. You could handle the exception within the current method...
else if(option == 5){
try {
SaveFile();
} catch (IOException exp) {
// Handle the exception, tell the user, roll back, what ever
// At the very least use exp.printStackTrace()
}
}
or declare the current method as throwing an IOException like the SaveFile method does
Your SaveFile method is also, potentially, leaving the file open...
If the file writing process fails for some reason, toTextFile.close may never be called, instead, you should take advantage of the try-finally block, for example
public static void SaveFile() throws IOException{
System.out.println("Saving File!");
FileWriter toTextFile = null;
try {
toTextFile = new FileWriter("output.txt");
for(x=0;x<new_num_book;x++){
toTextFile.write(name[x]);
}
} finally {
try {
toTextFile.close();
} catch (Exception exp) {
}
}
}
or if you're using Java 7+, you can make use of the try-with-resources functionality, for example...
public static void SaveFile() throws IOException{
System.out.println("Saving File!");
try (FileWriter toTextFile = new FileWriter("output.txt")) {
for(x=0;x<new_num_book;x++){
toTextFile.write(name[x]);
}
}
}
You may also want to have a read of Lesson: Exceptions and Code Conventions for the Java TM Programming Language, which will make it easier for people to read your code and for you to read others
So I have a method to write a string to a file:
public static void saveStringToFile(String path, String string) {
File file = new File(path);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter out = null;
try {
out = new FileWriter(path);
out.write(string);
if (out != null) {
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And my test class with the following setUp method which runs before each test (to delete the testfile before each one):
public static final String TEST_FILE = "somefile.xml";
//...
#Before
public void setUp() throws IOException {
if (MyCustomClass.fileExists(TEST_FILE)) {
new File(TEST_FILE).delete();
}
}
Each of my test tries to write something to the file using the method saveStringToFile(). It succeeds like for a couple of times, but a some random point I finally get the java.io.IOException: Access is denied. Got no idea why this happens - sometimes it occurs in test1, sometimes in test3...
It was working OK, when I was using Java7 FileIO, but I needed to migrate back to Java6...
Are you testing that you are able to create, write to and delete a file, or are you testing what is written to the file?
If the latter, then perhaps you should be mocking/overriding the saveStringToFile( ... ) method and instead focus on verifying that the code you're unit testing actually produces the correct output.
If the former, then I quite agree with #Omaha's suggestion that your test runner is likely running several tests in parallel.
Hope that helps.
There's some problems with the exception handling. The call to out.close() should be within a separate try-catch block inside a finally block. If an exception is thrown when writing to the file, the file is never closed.
I would recommend looking at something like Apache Commons IO which has many useful IO methods like FileUtils.writeStringToFile().
So, probably JUnit wasn't running it parrallel, cause as I suppose It doesn't do it by default.
The problem was in my readfile method:
private String readFile(String path) throws FileNotFoundException {
return (new Scanner(new File(path))).useDelimiter("\\Z").next();
}
To work fine I had to fix
private String readFile(String path) throws FileNotFoundException {
Scanner scanner = (new Scanner(new File(path)));
String s = scanner.useDelimiter("\\Z").next();
scanner.close();
return s;
}
The close() method for Scanner was the key...
I have a simple servlet where I write to a file if it has a queryparameter 'hello', and since this is a test I want to display the error the the webpage also.
IntelliJ is complaining that I am not catching the IOException, not sure what's wrong:
private static void WriteToFile(String filePath, String fileName, String fileData) {
FileWriter writer = null;
try {
writer = new FileWriter(fileName);
writer.write(fileData);
} catch(IOException ex) {
} finally {
if(writer != null) {
writer.close();
}
}
}
Also, in my exception, I noticed on the web most people write:
How can I output the error to the web page?
You're not catching IOException when you call writer.close(); in the finally block.
You're also completely swallowing any IOException thrown in the main code, which is a really bad idea. If something's goes wrong, you'll have no idea what's happening.
I would personally suggest that you let that method throw the exception to the caller:
private static void writeToFile(String filePath, String fileName,
String fileData) throws IOException {
FileWriter writer = new FileWriter(fileName);
try {
writer.write(fileData);
} finally {
writer.close();
}
}
Note that if the try block throws an exception and the finally block does, you'll effectively "lose" the original exception. You may want to suppress exceptions throw when closing.
Or just use Guava which makes all of this simpler anyway with its Files class.
Or if you're using Java 7, you could use a try-with-resources statement.
(I note that you're ignoring filePath by the way - why?)
You can write in catch block too : writer.write(errorMessage);
or you may redirect to Error page if error occured