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