[英]Retrieving data from byte Array
I'm trying to implement the tail program and want to print the last n bytes of a file. 我正在尝试实现tail程序,并希望打印文件的最后n个字节。 I've used a RandomAccessFile variable to store the data from the text file. 我使用了RandomAccessFile变量来存储文本文件中的数据。 When I try to retrieve the data and print it to the console, I'm getting something like this: 当我尝试检索数据并将其打印到控制台时,我得到的是这样的:
-n1
65109710979710979710810979710810510510979710910659711010510979711410011897114107109797114100119111108102106597114111110
How does on properly retrieve the data from the byte array? 如何正确地从字节数组中检索数据?
This is my code: 这是我的代码:
RandomAccessFile raf = new RandomAccessFile(file, "r");
byte[] b = new byte[n];
raf.readFully(b, 0, n);
for (int i = 0; i < n; i++) {
System.out.print(b[i]);
}
You are printing the byte
value. 您正在打印byte
值。 To convert eg an array of bytes to a String
that you can print on System.out.println
try the following: 要将字节数组转换为可以在System.out.println
打印的String
,请尝试以下操作:
System.out.println(new String(b));
If you wish to convert each byte
(as in your loop) to a printable char
you can do the following conversion: 如果希望将每个byte
(如循环中一样)转换为可打印char
,则可以执行以下转换:
for (int i = 0; i < 10; i++) {
char c = (char) (b[i] & 0xFF);
System.out.print(c);
}
A byte
is simply one byte in size (8 bits) whereas a char
in Java i 16 bits (2 bytes). 一个byte
大小仅为1个字节(8位),而Java i中的char
为16位(2个字节)。 Therefore the printed bytes does not make sense, it is not an entire character. 因此,打印的字节没有意义,它不是整个字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.