How to open a .dat file in java program

后端 未结 5 1400
时光取名叫无心
时光取名叫无心 2020-12-10 19:09

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, b

5条回答
  •  隐瞒了意图╮
    2020-12-10 19:49

    A .dat file is usually a binary file, without any specific associated format. You can read the raw bytes of the file in a manner similar to what you posted - but you will need to interpret these bytes according to the underlying format. In particular, when you say "open" the file, what exactly do you want to happen in Java? What kind of objects do you want to be created? How should the stream of bytes map to these objects?

    Once you know this, you can either write this layer yourself or use an existing API (assuming it's a standard format).

    For reference, your example doesn't work because it assumes that the binary format is a character representation in the platform's default charset (as per the InputStreamReader constructor). And as you say it's binary, this will fail to convert the binary to a stream of characters (since, after all, it's not).

    // BufferedInputStream not strictly needed, but much more efficient than reading
    // one byte at a time
    BufferedInputStream in = new BufferedInputStream (new FileInputStream("news.dat"));
    

    This will give you a buffered stream which will return the raw bytes of the file; you can now either read and process them yourself, or pass this input stream to some library API that will create appropriate objects for you (if such a library exists).

提交回复
热议问题