简体   繁体   English

Java从二进制文件读取

[英]Java reading from binary file

I have some calculated data (floats and integers), which is written to a 12mb file like this 我有一些计算出的数据(浮点数和整数),像这样写到12mb文件中

DataOutputStream os3;
os3 = new DataOutputStream(new FileOutputStream(Cache.class.getResource("/3w.dat").getPath()));
...... (some loops)
     os3.writeFloat(f);
     os3.writeInt(r);
os3.close();

And after that I read it this way 然后我以这种方式阅读

DataInputStream is3;
is3 = new DataInputStream(new FileInputStream(Cache.class.getResource("/3w.dat").getPath()));
...... (same loops)
     is3.readFloat();
     is3.readInt();
is3.close();

So, I wrote file only once on Windows 7. After that I only read it while app starts. 因此,我在Windows 7上只写了一次文件。此后,我仅在应用启动时读取了文件。 File reading works fine on Windows 7, but when I try do to it on Ubuntu, I get EOF exception (code and file are the same). 在Windows 7上文件读取工作正常,但是当我尝试在Ubuntu上读取文件时,出现EOF异常(代码和文件相同)。

I suspect problem may be caused by some NaN values written to the file. 我怀疑问题可能是由写入文件的某些NaN值引起的。

BTW. 顺便说一句。 While debugging I figured out that on ubuntu reading process runs about 15% of loop and throws an exception. 在调试时,我发现在ubuntu上读取过程会运行大约15%的循环并引发异常。 All values it reads are "0.0", but file doesnt contain zeros. 它读取的所有值均为“ 0.0”,但文件不包含零。

The problem should be the different of line break between Linux and Windows. 问题应该是Linux和Windows之间的换行符不同。 As mentioned by Clark, just replace the \\n with \\r\\n and the end of line character could resolve this. 正如Clark所提到的,只需将\\ n替换为\\ r \\ n,并且行尾字符可以解决此问题。 You can use Notpad++ to simplify this work. 您可以使用Notpad ++简化此工作。 Just click on Menu : 只需点击菜单:

Edit -> EOL conversion -> Convert to UNIX format 编辑-> EOL转换->转换为UNIX格式

It might be also a problem of encoding. 这也可能是编码问题。 If you'are using Windows, the default encoding is Windows-1252 or so called CP-1252, which is specially microsoft thing and cannot be recognized on Linux. 如果您使用的是Windows,则默认编码为Windows-1252或所谓的CP-1252,这是一种特殊的微软工具,在Linux上无法识别。 Just change it into an encoding like UTF-8 which can be recognized by all OS. 只需将其更改为UTF-8之类的编码即可被所有操作系统识别。 Using Notpad++: 使用Notpad ++:

Encoding -> Convert to UTF-8 编码->转换为UTF-8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM