使用缓冲读取器获取不同字节的java
当我将一些字节放入客户机socketOutputStream
并将它们传递给服务器socket时,出现了一个问题。使用BufferedReader
我想读取这些字节,但read()方法会获取字符,因此在发送范围<-128,-1>...
中的字节时,通常会获得不同的值。如何将这些字符转换为我想要的字节
public class Client {
public static void main(String[] args) {
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
s = new Socket("localhost", 3000);
is = s.getInputStream();
os = s.getOutputStream();
int read;
String str = "";
while ((read = is.read()) != '\n') {
str += (char) read;
}
System.out.println(str);
ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.BIG_ENDIAN);
b.putInt(430);
byte[] message = b.array();
for (int i = 0; i < message.length; i++) {
System.out.println(message[i] + " ");
}
os.write(message);
} catch (Exception ex) {
}
}
}
class Robot extends Thread {
private Socket s;
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(3000);
while (true) {
Socket s = ss.accept();
Robot srv = new Robot();
srv.s = s;
srv.start();
}
} catch (NumberFormatException numberEx) {
System.out.println("Port of port is not integer");
} catch (IOException ioEx) {
System.out.println("Input connection problem");
} finally {
try {
ss.close();
} catch (IOException ex) {
ex.printStackTrace();
Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public void run() {
BufferedReader is = null;
OutputStream os = null;
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = s.getOutputStream();
os.write("Send me data:\n".getBytes());
int b;
while ((b = is.read()) != -1) {
System.out.println((byte) b + " ");
}
} catch (Exception ex) {
}
}
}
# 1 楼答案
读取器将接收到的字节转换为字符,并使用系统属性
file.encoding
(您可以更改它)如果您需要字符(字符串),则必须使用已知编码(如UTF-8)对其进行解码和编码。在客户端和服务器上应该(必须)相同
如果你只需要字节(没有字符,没有字符串),你应该只使用流,没有读卡器