Java bites! Er, bytes. Yeah...
Gargh!
Trying to get a basic little app to work in Java - simple: read in file, perform some operations (display, reverse, rename, encrypt). I've got it all working (except for the encrypt part) while reading the file into a CharBuffer, but I'm trying to convert to a ByteBuffer to do the encription...
I've got it loading properly, but the display function always kicks out "0 - Exit" at the end when casting the bytes to chars; it's causing some real problems when reversing the order of bytes in the reverse function...
Anyone know how to troubleshoot this? Is it a matter of eliminating an eof character from the inputstream, or testing the last bytes for a specific value (which, for the life of me, I cannot think of).
If anyone is bored enough and home on a Friday night, my code follows:
public void showFile() throws IOException{
// display contents of file
FileChannel inChannel = (new FileInputStream(fileName)).getChannel();
originalBytes.clear();
// ByteBuffer obj declared earlier
originalBytes.allocate((int)inChannel.size());
while(inChannel.read(originalBytes) != -1){
// read bytes into buffer
}
originalBytes.flip();
inChannel.close();
// now, convert bytes to chars and output
while (originalBytes.hasRemaining()){
System.out.print( (char) (originalBytes.get() & 0xFF) );
}
}
public void reverseFile(){
// reverse the file
originalBytes.rewind();
// declare 2nd buffer
reverseBytes.allocate(originalBytes.limit());
// read first buffer into second in reverse order
for (int i = originalBytes.limit(); i <=0; i--){
reverseBytes.put(i, originalBytes.get());
}
try{
FileChannel outChannel = (new FileOutputStream(fileName)).getChannel();
outChannel.write(reverseBytes);
outChannel.close();
originalBytes.clear();
System.out.println("The file has been reversed. Please select option 2 to view the results.\n");
} catch (IOException ioe){
System.out.println("Write to file failed.");
}
}
Any help appreciated!