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();
	}  
  }
}

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

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

This article has been dead for over six months. Start a new discussion instead.