如何限制在Java中的文件大小 [英] How to limit the file size in Java

查看:751
本文介绍了如何限制在Java中的文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造我的应用程序的文件,我不断在写一些内容到这个文件。

但我的文件达到一定规模后,让说100行,我要删除的第一行,并写入新线的底部。

的要求是我的文件应得到限制,但应保持我写在以文件的最新内容。

请让我知道如果它可能在Java中?请让我知道,如果有任何替代做到这一点。


解决方案

  

请让我知道如果它可能在Java中?


这不能以简单的方式来完成。只能截断一个文件的最后部分。 (这是一个继承限制从底层的文件系统,并且由于同样的原因,为什么你不能的插入的字节在文件的中间。)

您的可以的手动做到这一点:


  1. 搞清楚的字节长度, N ,第一行的。

  2. 对于 I = N ...文件的长度

      在pos
    1. 字节写入 I 来POS 我 - N


  3. 文件截断长度文件长度 - N


  

请让我知道,如果有任何替代做到这一点。


我建议你使用的是循环缓冲区或类似的东西解决。尽管如此,虽然,你会惹上麻烦,如果不是所有的线条都同样长,除非你保存在内存缓冲区,它转储到(已清除)文件。

I am creating a file in my application and I am keep on writing some content in to this file.

But after my file reaches to some size, let say 100 lines, I want to erase the first line and write the new line to the bottom.

The requirement is my file should be limited, but it should maintain the latest content that I have written in to file.

Please let me know if its possible in Java? Please let me know if there's any alternative to do this.

解决方案

Please let me know if its possible in Java?

This can't be done in a simple way. You can only truncate the last part of a file. (This is an inherit limit from the underlying file system, and due to the same reasons as to why you can't insert bytes in the middle of a file.)

You can do it manually by:

  1. Figuring out the byte-length, n, of the first line.
  2. For i = n ... length of file

    1. Write byte at pos i to pos i - n

  3. Truncate the file to length length of file - n.

Please let me know if there's any alternative to do this.

I suggest you solve it using a cyclic buffer or something similar. Still though, you'd get into trouble if not all lines are equally long, unless you keep the buffer in memory, and dump it to (a cleared) file.

这篇关于如何限制在Java中的文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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