简体   繁体   English

Java等效于.net FileStream

[英]java equivalent of .net FileStream

I have a small .Net library that I would like to port to java. 我有一个小的.Net库,我想移植到Java。 Part of the requirement for this library is that it should serialize state into a file on disk and this file should remain "open" so other instances of the library cannot access this file but most create their own instance. 此库的部分要求是,它应该将状态序列化为磁盘上的文件,并且该文件应保持“打开”状态,以便该库的其他实例无法访问该文件,但大多数会创建自己的实例。 In C# I have used the FileStream which is opened with FileShare.None to guard against others reading/writing to the file. 在C#中,我使用了与FileShare.None一起打开的FileStream来防止其他人读取/写入文件。 When holding the FileStream I can read and write to the file, calling Flush() to write to disk and using SetLength(..) I can shorten an already existing file after write content. 当持有FileStream时,我可以读写文件,调用Flush()写入磁盘,并使用SetLength(..)可以在写入内容后缩短已经存在的文件。

In java I am not certain which class offers the most similar properties. 在java中,我不确定哪个类提供最相似的属性。 The RandomAccessFile is my best bet but since I am not exactly well-versed in java I might be overlooking some better suited class or some caveat with RandomAccessFile. RandomAccessFile是我最好的选择,但是由于我不太精通Java,因此我可能会忽略一些更合适的类或对RandomAccessFile的一些警告。

Check out FileWriter, read the API-Docs to see whether it suits your needs. 查看FileWriter,阅读API文档以查看它是否适合您的需求。

FileWriter is meant for writing streams of characters. FileWriter用于编写字符流。 For writing streams of raw bytes, consider using a FileOutputStream. 要写入原始字节流,请考虑使用FileOutputStream。

Reading your post again, i actually think this might answer your question: 再次阅读您的文章,我实际上认为这可能会回答您的问题:

How to prevent file from being overridden when reading and processing it with Java? 使用Java读取和处理文件时,如何防止文件被覆盖?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM