这是我编写的一些代码,用于连续重复地写入多个文件 channel 。
文件已创建,没有错误,但没有写入任何内容。 重要的部分是缓冲区写入的位置:“listofChan[j].write(buff);” 。为什么这不起作用?
FileChannel[] listofChan = new FileChannel[mStackHeight];
FileOutputStream[] outputFiles = new FileOutputStream[mStackHeight];
ByteBuffer buff = ByteBuffer.allocate(mStackWidth * 2); //2 byte integers
ShortBuffer SB = buff.asShortBuffer();
ImageProcessor ip;
try {
for (int i = 0; i < mStackHeight; i++) {
outputFiles[i] = new FileOutputStream(new File(mSavepath + "\\T_" + i + ".dat"), true);
listofChan[i] = outputFiles[i].getChannel();
}
System.out.println("File streams created successfully.");
for (int z = 0; z < mStackSz; z++) { //all slices in stack
ip = mStack.getProcessor(z + 1);
ip = ip.convertToShortProcessor();
short[] Pixels = (short[]) ip.getPixels();
for (int j = 0; j < mStackHeight; j++) { //all lines in one frame
SB.clear();
SB.put(Pixels, j * mStackWidth, mStackWidth);
listofChan[j].write(buff);
}
System.out.println("line " + z + " " + listofChan[mStackWidth-1].position());
// System.out.println("Image line : " z-1+ p/mStackWidth );
}
for (int i = 0; i < mStackHeight; i++) {
outputFiles[i].close();
}
System.out.println("Buffer contents written to file.");
} catch (IOException e) {
System.out.println("File IO exception : " + e.toString());
}
好的,我找到了解决方案:
我需要在 SB.clear();
上方的一行添加 buff.clear()
因为写入ByteBuffer
后,读/写位置位于缓冲区的末尾,因此无法从更远的地方写入。对于 IntBuffer
来说也是如此,这也需要单独重置,因为两个 View 的位置是独立的(我假设......)。
最佳答案
我认为您需要在写入之前翻转字节缓冲区。它仍处于读取/放置模式。
关于java - 重复写入多个文件 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36663381/