Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

DataInputStream and Strings

 
John Martin
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using a DataInputStream to read the database file. However, I am confused at how to read String values as there are no methods listed. The readUTF() (which does return a String) did not function properly.

A reference guide suggests using a ObjectInputStream, but that class has the same methods as DataInputStream.

Also, when reading the 2 byte vlaue for number of fields for each record I received a large value.
 
Daniel Dalton
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at java.io.RandomAccessFile. You can read data into a byte[] and then convert that to a String. It also has various other useful methods that should enable you to read the file fairly readily.
 
Muthaiah Ramanathan
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using a DataInputStream to read the database file. However, I am confused at how to read String values as there are no methods listed. The readUTF() (which does return a String) did not function properly.


While many of them prefer RandomAccessFile, I also use DataInputStream to read from the FileInputStream. You can first read the specified number of bytes and then convert it into a String (byte[]->chars->String).

Also, when reading the 2 byte vlaue for number of fields for each record I received a large value.

Try the 'readInt()' method of DataInputStream!
 
John Martin
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey All - Thanks!

I found some old code Andrew had posted. 'Search' feature came thru on my first question.

Basically just cast each long value you readin for the field name:

//using dataInputStream
byte[] fldName = new byte[fldSz];
long fldNameValue = dis.read(fldName);
String fieldName = (new String(fldName))


However I am still getting too largge a value for the Number of Fields:




Output:

cookie = 538968322
# fields 8199.

I dont think the evaluator will allow me to hard code a 7 for # fields!


Thx for any ideas.
 
John Martin
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note: I do see that this has been a recurring question over that past few years.
 
John Martin
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note: My output is now 'normal'. I am not sure what the problem was. The original file may have been corrupted? Not sure.

Thanks for the insights!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic