Solved

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

Posted on 2011-03-11
10
432 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
Comment Utility
You need to close the Writer each time
0
 
LVL 92

Assisted Solution

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

Expert Comment

by:objects
Comment Utility
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
Comment Utility
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
Comment Utility
You're calling write without initializing the Writer again
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 92

Expert Comment

by:objects
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
:)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
scoresSpecial  challenge 13 40
sumHeights  challenge 17 59
Books that can get me started on JAVA 2 52
word0 challenge 4 52
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

771 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

9 Experts available now in Live!

Get 1:1 Help Now