重写程序已使用的文件
我想知道是否有一种方法可以确定程序中是否打开了任何流?
我正在使用我的一些代码和其他一些代码,我的目标是能够多次写入同一个文件,每次都擦除并重写。然而,我认为在某个地方,属于另一个组的代码可能忘记关闭流,或者 Java 无法处理它,也许?它始终写入文件的末尾,而不是写入空白文件的开头。如果程序已打开它,它不会删除,也无法重命名。
如果这是一个开放流问题,我想关闭该流(我已经浏览了代码,并且似乎找不到开放流)。或者,如果 Java 无法处理它,是否有一个好方法(除了创建销毁方法之外)让我能够重置/杀死要重新实例化的对象?
或者有没有办法可以...将文件设置为空并删除它?或者我应该尝试打开该文件,删除它并将偏移量设置为 0?
任何提示都会很好
I was wondering if there was a way to determine if any streams are open in a program?
I am using some of my code and some of another, and my goal is to be able to write to the same file multiple times, erasing it and rewriting every time. However, I think somewhere, the code belonging to this other group may have forgotten to close a stream, or that Java cannot handle it, maybe? It always writes at the end of the file, instead of at the beginning of a blank file. It will not delete and I cannot rename it if it has already been opened by the program.
If it is an open stream problem, I want to close the stream (which I have gone through the code, and cannot seem to find the open stream). Or if Java cannot handle it, is there a good way (besides making destroy methods) for me to be able to reset/kill objects to be reinstanciated?
Or is there a way to maybe...set the file to null and that erases it? Or should I try to open the file, erase it and set the offset to 0?
any tips would be nice
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一些可能对您有用的好代码:
希望这有帮助!
Heres some good code that might be usefull to you:
Hope this helped!
@John Detter,我已经尝试了其中的很大一部分,尽管这是一些很好/有用的代码。
我通过在单独的线程中打开文件(当我知道我没有从/写入它时)作为 RandomAccessFile 来解决这个问题。我得到了文件的长度,然后调用 raf.skipBytes(length) 并删除了该文件。
还有一些其他奇怪的事情随之而来,但它对我有用。
@John Detter, i had already tried a significant portion of that, though that is some good/helpful code.
I solved it by opening the file in a separate thread (when I knew I was not reading/writing from/to it) as a RandomAccessFile. I got the length of the file, then called raf.skipBytes(length) and it erased the file.
There are some other weird things that go along with it, but it works for me.