编写大量的小文件

hc2pp10m  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(305)

我已经编写了将字符串写入文件的java代码。字符串的大小很难达到10kb。
下面是我写的写文件的代码。我写了三种写入文件的方法。

void writeMethod(String string, int m)
{
    if (m == 1) 
    {
        FileChannel rwChannel = new RandomAccessFile(filePath, "rw").getChannel();
        ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, string.length() * 1);
        wrBuf.put(string.getBytes());
        rwChannel.close();
    }

    if (m == 2)
    {
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        fileOutputStream.write(string.getBytes());
        fileOutputStream.close();
    }

    if (m == 3)
    {
        FileWriter bw  new FileWriter(filePath);
        bw.write(string);
        bw.close( );
    }
}

**忽略错误

我从3个线程调用上述函数,每个线程调用一个方法。我不知道哪一个最快。如果不在这些方法中,哪一个是好的。我要写17000000个文件。

9rygscc1

9rygscc11#

你也可以试试 java.nio.file 打包为测试目的的方法之一。
比如:

Path path = Paths.get(filePath);
Files.write(path, string.getBytes(), null);

相关问题