简体   繁体   English

从文件(java)读取ascii特征和整数

[英]Read ascii charactres and ints from file (java)

I'm doing a project where I my code has to be the most efficient possible, and I need to read ascii chars and ints from a file. 我正在做一个项目,我的代码必须尽可能高效,并且我需要从文件中读取ascii字符和整数。 The problem (I think) is that when I read chars it reads in UTF8 beacuse it only reads half the times it should. 问题(我认为)是,当我读取chars时,它以UTF8读取,因为它只读取应有的一半时间。

I tried with DataInputStream but it doesnt work. 我用DataInputStream尝试过,但是没有用。 Also I check the RandomAccessFile but it reads in UTF8. 我也检查RandomAccessFile,但是它读入UTF8。 The Scanner throws an InputMismatchException when I tried to read two bytes and convert them to char. 当我尝试读取两个字节并将其转换为char时,扫描程序会引发InputMismatchException。

Is it that the only option is to do this by hand? 唯一的选择是手动执行此操作吗?

Thanks in advance 提前致谢

Read one byte at once. 一次读取一个字节。 It will be the value you want. 这将是您想要的价值。 For example, with RandomAccessFile read() method: 例如,使用RandomAccessFile read()方法:

read() Reads a byte of data from this file. read()从此文件读取一个字节的数据。 The byte is returned as an integer in the range 0 to 255 (0x00-0x0ff). 该字节以0到255(0x00-0x0ff)范围内的整数形式返回。 This method blocks if no input is yet available. 如果尚无可用输入,则此方法将阻塞。

Example: 例:

int asciiValue randomAccessFile.read();

Then you can cast ìnt to char 然后您可以将ìntchar

char character = (char) asciiValue;

I found out what the problem is. 我发现了问题所在。 The thing is that when you write chars and ints using BufferedWriter, it converts all to char, which makes it impossible to read ints as a type directly from file. 事实是,当您使用BufferedWriter编写char和int时,它将全部转换为char,这使得无法直接从文件中读取int作为类型。 I'll try writing with a DataOutputStream, using the methods to direclty write ints and chars. 我将尝试使用DataOutputStream进行编写,并使用直接编写int和chars的方法。

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

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