Solved

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

Posted on 2011-03-11
10
466 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

Increase Agility with Enabled Toolchains

Connect your existing build, deployment, management, monitoring, and collaboration platforms. From Puppet to Chef, HipChat to Slack, ServiceNow to JIRA, Splunk to New Relic and beyond, hand off data between systems to engage the right people.

Connect with xMatters.

Question has a verified solution.

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

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

691 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