UDPおよび配列に関するtoStringメソッド
public class chatDialog {
public static void main(String[] args) throws Exception, IOException {
System.out.println(" :");
// System.out.println(InetAddress.getByName("download.filesfrog.com")
// .getHostAddress());
// byte[] buf = {1,1,2,2,3,2};
// System.out.println(new String(buf));
// System.out.println(Arrays.toString(buf));
// System.out.println(buf.toString());
DatagramSocket ds = new DatagramSocket(1233);
new Thread(new receive(ds)).start();
// IP
InetAddress ia = InetAddress.getByName("yun-pc");//yun-pc localHost 127.0.0.1
new Thread(new send(ia)).start();
}
}
class receive implements Runnable{
DatagramSocket ds ;
public receive(DatagramSocket ds) {
super();
this.ds = ds;
}
public void run() {
try {
while (true) {
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
// IP IP127.0.0.1
String IP = dp.getAddress().getHostAddress();
byte[] get = dp.getData();
System.out.println(IP + ":\r
" + new String(get));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class send implements Runnable{
InetAddress ia;
private DatagramSocket s;
send(InetAddress ia){
this.ia = ia;
}
public void run() {
try {
s = new DatagramSocket();
while (true) {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String line = br.readLine();
byte[] buf = line.getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, ia,
1233);
s.send(dp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
配列を文字列バイト配列に変換する変換方法はnew String(byte[],start,end)のみです.
文字配列にはnew String(char[],start,end)とStringが2種類ある.valueOf(char[]名);
配列ツールクラスArraysのtoString(byte[])メソッドと配列自体のtoString()メソッド
System.out.println(Arrays.toString);//[-60, -29, -70, -61]
byte[] buf = {-60, -29, -70, -61};
System.out.println(new String(buf));//こんにちは
System.out.println(Arrays.toString(buf));//[-60, -29, -70, -61]
System.out.println(buf.toString());//[B@15bdc50