-
Java: File I/O
The following program will throw an exception at the indicated section. Don't know how to fix it
Code:
iimport java.io.*;
public class MainTwo
{
private RandomAccessFile ioFile;
public MainTwo( String file )
{
try
{
ioFile = new RandomAccessFile( file, "rw" );
}
catch ( FileNotFoundException e )
{
System.err.println ( "Mmm?" );
}
}
public void write( String str, int length ) throws IOException
{
StringBuffer buffer = new StringBuffer( str );
buffer.setLength( length );
ioFile.writeChars( buffer.toString() );
}
public String read( int length ) throws IOException
{
char arr[] = new char[ length ];
char temp;
for ( int count = 0; count < length; count++ )
{
temp = ioFile.readChar();
arr[ count ] = temp;
}
return new String( arr ).replace( '\0', ' ' );
}
public void kill()
{
try
{
if ( ioFile != null )
ioFile.close();
}
catch ( IOException e )
{
System.err.println( "Great?" );
}
}
public static void main( String args[] )
{
MainTwo app;
String msg;
String anotherMsg;
app = new MainTwo( "Data.bin" );
msg = "Got Java?";
try
{
app.write( msg, msg.length() );
}
catch ( IOException e )
{
System.err.println( "What the?" );
}
try
{
anotherMsg = app.read( msg.length() );
}
catch ( IOException e )
{
System.err.println( "Ouch" );
}
app.kill();
}
}
-
your getting an exception because the file pointer is at the end of the file after writing (ie. there is nothing to read).
btw: do you have to read one byte at a time for some reason? there are easier ways to do such things.
see: http://java.sun.com/j2se/1.4.2/docs/...ccessFile.html
-