写入文件的最快方法? [英] Fastest way to write to file?

查看:30
本文介绍了写入文件的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个接受 FileString 的方法.它将文件替换为以该字符串作为内容的新文件.

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.

这是我做的:

public static void Save(File file, String textToSave) {

    file.delete();
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write(textToSave);
        out.close();
    } catch (IOException e) {
    }
}

但是它非常缓慢.有时需要一分钟以上.

However it is painfully slow. It sometimes takes over a minute.

如何编写包含数万到一百万个字符的大文件?

How can I write large files with tens of thousands to maybe up to a million characters in them?

推荐答案

确保分配足够大的缓冲区:

Make sure you allocate a large enough buffer:

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

您运行的是哪种操作系统?这也可以产生很大的不同.然而,花分钟来写出一个小于大大小的文件听起来像是一个系统问题.在 Linux 或其他 *ix 系统上,您可以使用诸如 strace 之类的东西来查看 JVM 是否进行了大量不必要的系统调用.(很久以前,Java I/O 非常愚蠢,如果您不小心,它会发出疯狂数量的低级 write() 系统调用,但是当我说很长一段时间以前"我的意思是 1998 年左右.)

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

编辑 —请注意,Java 程序以简单的方式编写一个简单的文件,但速度非常慢,这种情况本质上是一种奇怪的情况.您能判断在写入文件时 CPU 是否负载过重吗?不应该;这种事情应该几乎没有 CPU 负载.

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.

这篇关于写入文件的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆