Writting an object in a file. Best way

79 views Asked by At

I have a problem with time.

I currently develop an app in Java where I have to make a network analyzer.

For that I use JPCAP to capture all the packets, and write them in a file, and from there I will put them bulk in DB.

The problem is when I am writting in file the entire object, like this,

UDPPacket udpPacket = (UDPPacket)packet
wtf.writeToFile("packets.txt",udpPacket +"\n");

everything is working nice and smooth, but when I try to write like this

    String str=""+udpPacket.src_ip+" "+udpPacket.dst_ip+""
+udpPacket.src_port+" "+udpPacket.dst_port+" "+udpPacket.protocol +
" Wi-fi "+udpPacket.dst_ip.getCanonicalHostName()+"\n";
     wtf.writeToFile("packets.txt",str +"\n");

writting in file is during lot more time.

the function to write in file is this

public void writeToFile(String name, String str){
        try{
            PrintWriter writer = new PrintWriter(new FileOutputStream(new File(name),this.restart));
            if(!str.equalsIgnoreCase("0")){
                writer.append(str);
                this.restart=true;
            }
            else {
                this.restart=false;
                writer.print("");
            }
            writer.close();
        } catch (IOException e) {
          System.out.println(e);
        }
    }

Can anyone give me a hit, whats the best way to do this?

Thanks a lot

EDIT:

7354.120266 ns - packet print

241471.110451 ns - with StringBuilder

2

There are 2 answers

2
user207421 On

Keep the PrintWriter open. Don't open and close it for every line you want to write to the file. And don't flush it either: just close it when you exit. Basically you should remove your writeToFile() method and just call PrintWriter.write() or whatever directly when necessary.

NB You are writing text, not objects.

0
Paul F. On

I found the problem

as @KevinO said, getCanonicalHostName() was the problem.

Thanks a lot.