使用 Java 将字符串附加到 Windows 中的文件 [英] Atomic append string to file in Windows using Java

查看:45
本文介绍了使用 Java 将字符串附加到 Windows 中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个问题,小文件Windows 上的追加是原子的.

According to this question, small file appends on Windows are atomic.

我试图在 Scala/Java 中利用它来避免在将小整数附加到文件时锁定.

I am trying to leverage this in Scala / Java to avoid locking when appending a small int to a file.

我发现使用 FileOutputStream(..., true) 来自多个线程的写入是交错的,即使上面链接的问题表明它们应该是原子的.

I am finding that writes using FileOutputStream(..., true) from multiple threads are being interleaved, even though the question linked above suggests that they should be atomic.

可以在 在我的 github 上找到 Scala 中的测试工具一个>

A test harness for this in Scala can be found on my github

关键代码是:

def invoked(id: Int, path: String) = {
  val writer = new FileOutputStream(path, true)
  val bytes = (id.toString + ';').getBytes(Charset.defaultCharset())
  writer.write(bytes)
  writer.close()
}

...我希望调用"在没有锁定的情况下是线程安全的.

... I was hoping that "invoked" would be thread-safe without locking.

相同的 Java/Scala 代码在 Linux 上实现了原子文件追加(根据 这个问题 小文件追加在 POSIX 上是原子的),所以区别似乎在于 FileOutputStream 的本机实现.

The same Java/Scala code achieves atomic file appends on Linux (as per this question small file appends are atomic on POSIX), so the difference seems to be in the native implementations of FileOutputStream.

也许 FileOutputStream 没有将正确的标志传递给 Windows?有谁知道如何使这项工作?我是否必须编写 JNI DLL 才能使其工作,或者有没有办法使用 Java 的标准库来做到这一点?

Perhaps FileOutputStream is not passing the correct flags to Windows? Does anyone know how to make this work? Will I have to write a JNI DLL to get this to work, or is there a way I can do this with Java's standard libraries?

推荐答案

写操作行为取决于文件打开标志.在 Windows 上,您需要使用 FILE_APPEND_DATA 标志或使用特殊常量来实现追加.Posix 需要 O_APPEND 标志.尽管 Java 具有用于查看其源代码的 append 参数的 bool 值,但以下注释解释了 为什么它不起作用.

Write operation behavior depends on file opening flags. On Windows you need to use FILE_APPEND_DATA flag or use the special constants to achieve append. Posix require O_APPEND flag. Although Java has bool value for append parameter looking into its source code following comment explains why it does not work.

FileDispatcherImpl(boolean append) {
    /* append is ignored */
}

这篇关于使用 Java 将字符串附加到 Windows 中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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