【问题标题】:Apache Commons VFS - How does one set the size of a file...?Apache Commons VFS - 如何设置文件的大小......?
【发布时间】:2011-07-18 10:13:51
【问题描述】:

我似乎在 FileObject 或 FileContent 上找不到任何允许我在现有文件上设置新大小的方法。

FileContent.getSize() 没有对应的setSize()RandomAccessContent 确实有一些关于寻找的 cmets,但它似乎没有说明如果在结束前寻找某个地方然后简单地关闭文件,文件会缩小。

/**
 * Sets the file-pointer offset, measured from the beginning of this
 * file, at which the next read or write occurs.  The offset may be
 * set beyond the end of the file. Setting the offset beyond the end
 * of the file does not change the file length.  The file length will
 * change only by writing after the offset has been set beyond the end
 * of the file.
 * <br/>
 * <b>Notice: If you use {@link #getInputStream()} you have to reget the InputStream after calling {@link #seek(long)}</b>
 *
 * @param pos the offset position, measured in bytes from the
 *            beginning of the file, at which to set the file
 *            pointer.
 * @throws IOException if <code>pos</code> is less than
 *                     <code>0</code> or if an I/O error occurs.
 */
public void seek(long pos) throws IOException;

【问题讨论】:

  • 我可能错过了您的问题的重点,但更改文件大小的唯一方法是更改​​内容。简单地更改搜索点不会对文件进行任何更改。您想在某个时间截断文件吗?
  • 没有多少 api 允许例如通过简单地将文件大小设置为 0 而不是重新创建文件来清除文件。设置文件大小也可用于仅保留文件的开头并“删除”文件的其余部分,而无需创建另一个文件、复制、删除原始文件并将其重命名等。
  • 其他 api 是的,但不是你的问题所指的这个。仍然不确定您想要什么,尝试更清楚,有人可能会回答。如果您想截断本地文件,请尝试通过getLocalFile 对文件通道进行截断操作,这对您是否有用我不知道
  • @vickirk,我希望避免强制转换,因为这意味着我需要为每个不同的 vfs 文件系统设置特殊情况,我希望通过使用通用 API 来做到这一点。我想我可能需要做一些我认为你指向的事情,但是手指交叉。
  • 在回答您的原始评论时,是的,我想在某个时候截断!.. 很抱歉没有明确这一点...

标签: java apache-commons-vfs


【解决方案1】:

使用公共 API,您无法设置大小或截断任何文件。然而,一些专门的类型确实提供了一种可以使用的方法。也就是说,该方法也可能不公开,需要令人讨厌的反思。

【讨论】:

    【解决方案2】:

    如果您想使用setSize(int size) 设置大小,它会在某些API 中设置大小,但当size 小于file.getSize() 时可能会丢失一些数据。

    某些 API 仍允许通过将大小设置为 0 来截断文件,这意味着内容已被删除。它实际上并没有设置 size 属性,而是删除数据然后刷新 size 属性。

    为避免此类混淆,此 API 已删除 setSize(int size) 方法。

    但您仍然可以通过使用outputStream 引用在文件对象中附加或删除内容来间接设置大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 2010-11-23
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多