如何在java程序中打开一个.dat文件 [英] How to open a .dat file in java program

查看:810
本文介绍了如何在java程序中打开一个.dat文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拿了一个扩展名为.dat的文件。我需要在Java程序中读取这些数据,并将数据构建到我们定义的一些对象中。我尝试了以下,但它没有工作

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

有人能告诉我如何在java中执行此操作吗?一个 .dat 文件通常是一个二进制文件,没有任何特定的关联格式。您可以按照与发布内容相似的方式读取文件的原始字节,但是您需要根据基础格式来解释这些字节。特别是,当你说打开这个文件时,你想要在Java中发生什么?你想创建什么样的对象?一旦你知道这一点,你可以自己写这个图层,或者使用现有的API(假设它是一个标准格式) 。
$ b

为了便于参考,你的例子不起作用,因为它假定二进制格式是平台默认字符集中的字符表示(按照 InputStreamReader 构造函数)。正如你所说,它是二进制的,这将无法将二进制转换为字符流(因为毕竟,它不是)。

  // BufferedInputStream不是严格需要的,但是比读取
//一次一个字节更高效
BufferedInputStream in = new BufferedInputStream(new FileInputStream(news.dat));

这会给你一个缓冲流,它将返回文件的原始字节;你现在可以自己读取和处理它们,或者将这个输入流传递给一些库API,它将为你创建适当的对象(如果存在这样的库)。


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?

解决方案

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).

这篇关于如何在java程序中打开一个.dat文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆