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
Solved

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

Posted on 2011-03-11
10
452 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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
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:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

829 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