特别注意:int a = s.getBytes().length; 是获取字节数长度,不是字符串长度,否则汉字出现乱码
发送端:
import java.io.*;
import java.net.*;
public class Send {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
// File f = new File("D:/ccc.txt");
// FileInputStream fi = new FileInputStream(f);
// BufferedReader br=new BufferedReader(new InputStreamReader(fi));
// String s1 = "";
// while ((s1 = br.readLine()) != null) {
// int a = s1.getBytes().length;
// int count = a / 30;
// int left = a % 30;
// for (int i = 0; i < count; i++) {
// DatagramPacket dp = new DatagramPacket(s1.getBytes(), i * 30, 30,
// InetAddress.getByName("localhost"), 6668);
// ds.send(dp);
// }
// DatagramPacket dp = new DatagramPacket(s1.getBytes(), count * 30, left,
// InetAddress.getByName("localhost"), 6668);
// ds.send(dp);
// }
String s = "hello world,how are you ,i am fine, do dou want to go to the zoo?,我晕";
int a = s.getBytes().length;
int count = a / 30;
int left = a % 30;
for (int i = 0; i < count; i++) {
DatagramPacket dp = new DatagramPacket(s.getBytes(), i * 30, 30, InetAddress.getByName("localhost"),
6668);
ds.send(dp);
}
DatagramPacket dp = new DatagramPacket(s.getBytes(), count * 30, left, InetAddress.getByName("localhost"),
6668);
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
接收端:
import java.net.*;
public class Save {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(6668);
byte[] b = new byte[30];
while (true) {
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
byte[] data = dp.getData();
String string = new String(data, 0, dp.getLength());
System.out.println(string);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
URL文件下载:
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class Test {
public static void main(String[] args) {
BufferedInputStream bi = null;
BufferedOutputStream bo = null;
File f = new File("http://img06.tooopen.com/images/20160712/tooopen_sy_170083325566.jpg");
File file = new File("E:/", f.getName());
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
URL url = new URL("http://img06.tooopen.com/images/20160712/tooopen_sy_170083325566.jpg");
InputStream in = url.openStream();
bi = new BufferedInputStream(in);
FileOutputStream fo = new FileOutputStream(file);
bo = new BufferedOutputStream(fo);
int a = -1;
while ((a = bi.read()) != -1) {
bo.write(a);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bi.close();
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}