【问题标题】:How to write a byteArray into a File? [duplicate]如何将字节数组写入文件? [复制]
【发布时间】:2016-07-05 15:54:37
【问题描述】:

所以我正在尝试实现一种将 byteArray 插入文件的方法,并设置一个包含插入的 byteArray 的新 byteArray(如果这有意义的话)。以下是我的代码,但是我很确定出了点问题,因为我的测试失败了,我们将不胜感激。

public void writeBlock(int blockNum, AbstractDBFile f, AbstractBlock b)
            throws IOException {

    f.setCurBlockPos(blockNum);
    byte[] writeData = new byte[4096];
    int currentByte = f.getCurBlockPos() * 4096;
    File ourFile = new File(f.getFileName());
//  Block block = new Block();
    Path path = Paths.get(f.getFileName());
    Files.write(path, writeData, StandardOpenOption.WRITE); //Data is Written

    RandomAccessFile file = new RandomAccessFile(ourFile, "rw");
    FileChannel inChannel = file.getChannel();
    ByteBuffer bb = ByteBuffer.allocate(currentByte);
    inChannel.write(bb);
    while(inChannel.read(bb)>0){
    bb.flip();
    for (int i =0; i<bb.limit(); i++){
        writeData[i]=bb.get();
        b.setData(writeData);
    }
    bb.clear();
}
    inChannel.close();
    file.close();


}

【问题讨论】:

    标签: java file bytearray randomaccessfile


    【解决方案1】:

    我推荐使用 APACHE-COMMON-IO,它是一个很好的库来进行文件操作。这个库有很多方法可以用文件编写、复制、移动等。它易于使用。

    按照你的方法,我遇到了很多问题。但是现在 e 只使用这个库。

    祝你好运

    【讨论】:

      猜你喜欢
      • 2014-04-10
      • 2019-10-29
      • 2019-02-07
      • 1970-01-01
      • 2010-12-18
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多