-2

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?

4 Answers4

5

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();
        }
    }
}
Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • When you say use FileUtils.writeStringToFile w/o creating a method, what do you mean? – user2475261 Jun 11 '13 at 17:42
  • @user2475261 If you include `FileUtils` in your classpath, you can just say what I've written above (let me edit my answer to show you an example) – Daniel Kaplan Jun 11 '13 at 17:43
2

You could use one of the many logging frameworks available, like http://logging.apache.org/log4j/1.2/ for example

Zavior
  • 6,412
  • 2
  • 29
  • 38
1

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);
nachokk
  • 14,363
  • 4
  • 24
  • 53
0

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");
Stefan
  • 2,603
  • 2
  • 33
  • 62