Here is some code i made to write succesively and repetitively to multiple filechannels.
The files get made, there are no errors, but nothing gets written. The important part is where the buffer is written : "listofChan[j].write(buff);" . Why is this not working?
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());
}
Okay, I've found the solution:
I needed to add buff.clear()
on a line just above SB.clear();
because after writing the ByteBuffer
, the read/write postition is at end of the buffer, so it cannot be written from further. The same for the IntBuffer
, this also needs to be reset separately because the positions of both views are independent (I'm assuming ...).