Solved

Java: Trying to log a string to file, but it doesn't work

Posted on 2011-03-11
10
437 Views
Last Modified: 2013-11-24
Hi Guys - I'm creating a program that has a need to log HTTP traffic.  The traffic is read from socket to buffer to string.  Then the below method is invoked to write that string to file.  The code is pretty straight forward.

It uses java.io.filewriter to do the work.  filewriter has a method - write() that takes a String as an argument and according to the JavaDocs, should write it to the file linked to the filewriter.

The File object referenced (request) is created as a global variable, so the file exists.  When I compile and run the code, the file gets created and my debug shos that the method and proper code is being invoked, yet the file is empty.

Am I not using the FileWriter correctly?  What could be the problem?  Maybe there is a better way to do this?

In case you plan to suggest using Apache Commons, please don't - I can't use it for this project.
private void logIt(String toWrite, int a) throws IOException
    {
        //Determine if we are logging Client request traffic
        //or server reply traffic
        if (a == 0){
            FileWriter writer = new FileWriter(request, true);
            //Write to requestlog.txt
            writer.write(toWrite);
            debug("Client Request traffic logged");
        }else {
            //Write to requestlog.txt
            FileWriter writer = new FileWriter(reply, true);
            writer.write(toWrite);
            debug("Server Reply traffic logged");
        }
    }

Open in new window

0
Comment
Question by:southpau1
  • 5
  • 4
10 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 35113179
You need to close the Writer each time
0
 
LVL 92

Assisted Solution

by:objects
objects earned 250 total points
ID: 35113180
you need to close the writer
0
 
LVL 92

Expert Comment

by:objects
ID: 35113187
you'll also find it simpler to use a PrintWriter


            PrintWriter writer = new PrintWriter(new FileWriter(reply, true));
            writer.println(toWrite);
            writer.close();
0
 
LVL 7

Author Comment

by:southpau1
ID: 35113225
Ok that worked!  I close and it logs.  But now I get these errors and my entire program doesn't work..
java.lang.NullPointerException
	at java.io.Writer.write(Writer.java:140)
	at com.mba.proxylight.RequestProcessor.logIt(RequestProcessor.java:421)
	at com.mba.proxylight.RequestProcessor.access$1400(RequestProcessor.java:24)
	at com.mba.proxylight.RequestProcessor$RequestProcessorRunner.processChannel(RequestProcessor.java:237)
	at com.mba.proxylight.RequestProcessor$RequestProcessorRunner.run(RequestProcessor.java:121)
	at java.lang.Thread.run(Thread.java:662)

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35113242
You're calling write without initializing the Writer again
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 92

Expert Comment

by:objects
ID: 35113247
looks like you're passing null to your logit method, should test for that

if (request!=null) {
        if (a == 0){
            PrintWriter writer = new PrintWriter(new FileWriter(request, true));
            writer.println(toWrite);
            writer.close();
            debug("Client Request traffic logged");
        }else {
            PrintWriter writer = new PrintWriter(new FileWriter(reply, true));
            writer.println(toWrite);
            writer.close();
            debug("Server Reply traffic logged");
        }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 35113255
you can also simplify that a little

      if (toWrite!=null) {
            PrintWriter writer = new PrintWriter(new FileWriter(a==0 ? request : reply), true));
            writer.println(toWrite);
            writer.close();
      }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35113270
Try
private void logIt(String toWrite, int a) throws IOException {
        //Determine if we are logging Client request traffic
        //or server reply traffic
        FileWriter writer = null;

        try {
            if (a == 0) {
                writer = new FileWriter(request, true);
                //Write to requestlog.txt
                writer.write(toWrite);
                debug("Client Request traffic logged");
            } else {
                //Write to requestlog.txt
                writer = new FileWriter(reply, true);
                writer.write(toWrite);
                debug("Server Reply traffic logged");
            }
        } finally {
            try {
                writer.close();
            } catch (Exception e) { /* ignore */
            }
        }
    }

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35113280
Don't hide/trap null pointers. Find out why null is being passed if it is and change it
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35113296
:)
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mapAB Challlenge 35 123
Checkbox and ListView in Android Layout 4 56
maven project error 5 47
factorial example 4 34
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now