ここでは、複数のファイルチャネルに連続して繰り返し書き込むコードを示します。複数のFilechannelsへの繰り返しの書き込み
ファイルが作成され、エラーはありませんが、何も書き込まれません。 重要な部分はバッファが書き込まれる場所です: "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());
}
さて、私は解決策を見つけた:
私は理由ByteBuffer
を書き込んだ後だけSB.clear();
上の行にbuff.clear()
を追加するために必要な、読み取り/書き込みpostitionは、バッファの末尾にありますだから、それ以上は書き込むことができない。 IntBuffer
でも同じですが、両方のビューの位置が独立しているため、これも別々にリセットする必要があります(私は仮定しています...)。
'write()'の後に 'compact()'してください。 – EJP