从字符数组中删除所有空元素 [英] Removing all empty elements from an character array
问题描述
我有一个字符数组,一次最多可容纳50000个字符。此数组的内容来自套接字连接。但是,不保证此字符缓冲区不会包含任何空元素。然后我需要将此字符数组转换为String(例如new String(buffer);)。我的问题是,每当我从套接字收到一个不是50000长的缓冲区时,你如何从这个char数组或这个字符串中删除剩余或空元素?如果没有,你建议的最有效的方式是什么?
I have a character array that can hold maximum 50000 characters at a time. Contents of this array are coming through socket connections. However it is not guaranteed that this character buffer is not going to have any empty elements. Then I need to convert this character array into a String (e.g. new String(buffer);). My question is, whenever I receive a buffer from socket that is not 50000 long, how do you remove left over or empty elements from this char array or this String? If not, what is the most efficient way you would suggest?
/ 这是当前的实现 /
private BufferedReader is;
//Other code
public String readBufferUpdate() throws IOException {
char[] buffer =new char[50000];
is.read(buffer);
return new String(buffer);
}
//////这是使用ByteArrayOutputStream的实现
////// This is an implementation using ByteArrayOutputStream
public String readAuth() throws IOException {
int s;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
while ((s = is.read()) != -1) {
bao.write(s);
if (!is.ready())
break;
}
if (s == -1) {
return null;
}
String result = bao.toString();
return result;
}
当我需要读取大量数据时,这种实现非常慢。
This implementation is extremely slow when I need to read huge amount of data.
-----------------编辑
-----------------edit
(例如,服务器发送数据,但它可能不总是50000长字节但32822长字节然后我需要删除左数组元素)
(for example, server sends me data but it might not always be 50000 long bytes but 32822 long bytes then I need to remove left over array elements)
推荐答案
在缓冲区中读取 InputStream
的正确方法如下。
Correct way to read from an InputStream
in a buffer is as follows.
public String readBufferUpdate() throws IOException {
char[] buffer =new char[50000];
int bytesRead = is.read(buffer, 0, buffer.length);
return new String(buffer, 0, bytesRead);
}
这里你 is.read()
返回已读入 bytesRead
的字节数。只有那么多字节从缓冲区复制到 String
。
Here you is.read()
returns how many bytes have been read into bytesRead
. Only that many bytes are copied from the buffer to String
.
这篇关于从字符数组中删除所有空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!