【问题标题】:Java FileChannel bigger than its contentJava FileChannel 比它的内容大
【发布时间】:2015-01-02 17:46:28
【问题描述】:

我正在创建一个 fileChannel 来执行内存映射写入。此 fileChannel 的大小为 100 字节。我只写了 80 个字节。因此,当我稍后从该文件中读取时,它会在 and 中添加 5 个“0”。有没有办法设置大小或获取写入文件的大小?

非常感谢!!

public FileChannel create(String randomFile){
   // create file output stream
   RandomAccessFile raf;
   FileChannel fc = null;

   try {    
      raf = new RandomAccessFile(randomFile, "rw");
      fc = raf.getChannel();
      System.out.println("fc.size() "+ fc.size());      
   } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }
   return fc;
}

【问题讨论】:

  • 你为什么不直接使用FileChannel.open()
  • 我使用 FileChannel 创建一个 MappedByteBuffer.mbb = fc.map(MapMode.READ_WRITE, position, bufferSize); 然后写入该缓冲区

标签: java filechannel


【解决方案1】:

改用这个:

final Path path = Paths.get("thefile");
final FileChannel fc = FileChannel.open(path, StandardOpenOption.WRITE,
    StandardOpenOption.READ);

// then later:

fc.truncate(80L);

当然,别忘了.close()。理想情况下,您应该使用 try-with-resources 语句打开您的频道。

【讨论】:

  • 执行此操作时出现此错误:FileChannel 类型中的方法 open(Path, OpenOption...) 不适用于参数 (Path, FileChannel.MapMode)
  • 啊,好吧,快速浏览一下 javadoc 应该会告诉您出了什么问题,甚至实际上是错误。将FileChannel.MapMode.WRITE 替换为StandardOpenOption.WRITE
  • 对不起,你是对的。现在我遇到了无法将文件映射到内存的问题:MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, position, bufferSize);This throws an nonReadableChannel Exception,我不知道为什么...
  • 嗯,你确实指定了你想打开它来写而不是读;添加StandardOpenOption.READ 作为打开选项,应该这样做
  • 截断完成了我需要的工作,它将大小减少到写入的数量。我不知道这种方法。文件的打开方式实际上并不重要。
【解决方案2】:

我认为setLength() 是您正在寻找的。 Java doc.

【讨论】:

  • 这个也返回 100 个字节。在我开始写入文件之前。
猜你喜欢
  • 2015-09-04
  • 2022-10-20
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 2011-09-01
相关资源
最近更新 更多