Fastest way to write to file?

后端 未结 6 1896
难免孤独
难免孤独 2020-12-02 15:54

I made a method that takes a File and a String. It replaces the file with a new file with that string as its contents.

This is what I made

6条回答
  •  星月不相逢
    2020-12-02 16:29

    Make sure you allocate a large enough buffer:

    BufferedWriter out = new BufferedWriter(new FileWriter(file), 32768);
    

    What sort of OS are you running on? That can make a big difference too. However, taking a minute to write out a file of less-than-enormous size sounds like a system problem. On Linux or other *ix systems, you can use things like strace to see if the JVM is making lots of unnecessary system calls. (A very long time ago, Java I/O was pretty dumb and would make insane numbers of low-level write() system calls if you weren't careful, but when I say "a long time ago" I mean 1998 or so.)

    edit — note that the situation of a Java program writing a simple file in a simple way, and yet being really slow, is an inherently odd one. Can you tell if the CPU is heavily loaded while the file is being written? It shouldn't be; there should be almost no CPU load from such a thing.

提交回复
热议问题