Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a .dat file in java program

Tags:

java

file-io

I was handed some data in a file with an .dat extension. I need to read this data in a java program and build the data into some objects we defined. I tried the following, but it did not work

FileInputStream fstream = new FileInputStream("news.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

Could someone tell me how to do this in java?

like image 625
flyingfromchina Avatar asked Nov 30 '22 10:11

flyingfromchina


1 Answers

What kind of file is it? Is it a binary file which contains serialized Java objects? If so, then you rather need ObjectInputStream instead of DataInputStream to read it.

FileInputStream fis = new FileInputStream("news.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
// ...

(don't forget to properly handle resources using close() in finally, but that's beyond the scope of this question)

See also:

  • Basic serialization tutorial
like image 160
BalusC Avatar answered Dec 04 '22 22:12

BalusC