简体   繁体   English

在Java中转换为字符串之前,应如何终止char数组

[英]How should I terminate a char array before converting into a string in Java

I am reading a char array from a file in and then converting it too a string using the String constructor. 我正在从文件中读取一个char数组,然后使用String构造函数将其也转换为字符串。

read = fromSystem.read(b);
String s = new String(b);

This code has been in the program for ages and works fine, although until now it has been reading the full size of the array, 255 chars, each time. 这段代码已经存在于程序中很长时间了,并且可以正常工作,尽管到目前为止,它一直在读取数组的完整大小,每次255个字符。 Now I am reusing the class for another purpose and the size of what it reads varies. 现在,我正在将该类用于其他目的,并且它读取的内容各不相同。 I am having the problem that if it reads, say 20 chars, then 15, the last 5 of the previous read are still in the byte array. 我有一个问题,如果它读取的是20个字符,然后读取的是15个字符,则先前读取的最后5个仍在字节数组中。 To overcome this I added a null char at the end of what had been read. 为了克服这个问题,我在已读内容的末尾添加了一个空字符。

read = fromSystem.read(b);
if (read < bufferLength) {
    b[read] = '\0';
}
String s = new String(b);

If I then did 如果我那么做

System.out.println(b);

It works, the end of the buffer doens't show. 它有效,缓冲区的末尾不显示。 However, if I pass that string into a message dialog then it still shows. 但是,如果我将该字符串传递到消息对话框中,它仍然会显示。 Is there some other way that I should terminate the string? 还有其他终止字符串的方法吗?

Use: 采用:

String s = new String(b, 0, read)

instead. 代替。

You need to use the String constructor that allows you to specify the range of bytes that are valid in the byte array. 您需要使用String构造函数,该构造函数允许您指定字节数组中有效的字节范围。

String(byte[] bytes, int offset, int length); String(byte [] bytes,int偏移量,int长度);

Using it like this: 像这样使用它:

read = fromSystem.read(b);
String s = new String(b, 0, read);

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

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