954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Regarding PrintStream class

We want to write byte array to a file.The code given below works correctly for only one byte array.When we try to write more than one byte array,the previous byte array gets overwritten.
How can we achieve this?

import java.io.*;
import java.nio.*;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class MyLogger {

 ByteBuffer b1;
 public void logMessage(String msg,byte[] b)
  {		
		  int len=b.length;
		  b1=b1.wrap(b);
		  FileOutputStream out;
	      PrintStream p; 
		  try
          	{
               out = new FileOutputStream("c:\\MyLogFile.log")
	            p = new PrintStream( out );
		      for (int i=0;i<len;i++ )
			  {
				p.print (b1.get(i));
				p.print(" ");		
	   		  }
		      p.println (" ");
			  p.close();
           }
           catch (Exception e)
           {
                System.err.println ("Error writing to file");
           }


			Logger logger = Logger.getLogger("MyLog");
			FileHandler fh;
			String strFilePath ="c:\\MyLogFile.log"; 
			try 
			{
				fh = new FileHandler(strFilePath,true);
				logger.addHandler(fh);
				logger.setLevel(Level.ALL);
				SimpleFormatter formatter = new SimpleFormatter();
				fh.setFormatter(formatter);
				logger.log(Level.INFO,msg);
			 } catch (SecurityException e) {
			   e.printStackTrace();
			 } catch (IOException e) {
				 e.printStackTrace();
	}  
  }
}
srs_grp
Light Poster
34 posts since Sep 2008
Reputation Points: 9
Solved Threads: 0
 

a solution would be to look into the classes used to write and search for append.
an other, if you want to keep most of your code, is to (before you write) read the existing data, put that data and your new data in one big char array, and write that one, but I would suggest the first option

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

Why would you want to dump a byte array in a log file? Anyways, use a FileWriter in append mode and if it is *really* required, write out the byte array as a string [by looping over individual bytes and converting them to their String representation; use a StringBuilder].

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You