File与IO流,网络编程
文章目录
- 一、File类
- 1.创建File类的实例
- 2.路径
- 3.路径分隔符
- 4.使用
- 5.常用方法
- 二、IO流
- 1.流的分类
- 2.流的体系结构
- 3.使用
- 字符流的使用
- 读文件
- 使用read的重载方法
- 写文件
- 字节流的使用
- 指定路径下文件的复制
- 图片的复制
- 图片的加密
- 结论
- 处理流的使用
- 转换流(属于字符流)
- 缓冲流
- 实现非文本文件的复制
- 实现文本文件的复制
- 要求
- 说明
- 对象流
- 要求
- 序列化过程
- 反序列化
- 其他流的使用
- 标准的输入、输出流
- 练习
- 打印流
- 数据流
- 写出
- 读取
- 4.RandomAccessFile
- 实现数据的插入
- 三、网络编程
- 1.问题
- 2.IP和端口号
- 3.网络通信协议
- TCP
- 练习一
- 客户端
- 服务端
- 练习二
- 客户端
- 服务端
- 练习三
- 客户端
- 服务端
- UDP
- 发送者
- 接收者
- URL
一、File类
1.创建File类的实例
- File(String pathname)
- File(String parent, String child)
- File(File parent, String child)
File file=new File("D:\\下载\\amcharts_geodata_4.1.17\\geodata\\data");File file1=new File("D:\\下载\\amcharts_geodata_4.1.17\\geodata","data");File file2=new File(file1,"hello.txt");
2.路径
- 相对路径:相较于某个路径下,指明的路径。
- 绝对路径:包含盘符在内的文件或文件目录的路径
3.路径分隔符
- windows : \
- unix:/
public static final char separatorChar = fs.getSeparator();
4.使用
- File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
- File类声明在java.io包下
- File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成
- 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点".
5.常用方法
File file = new File("D:\\下载\\激活码");//创建一个与file同目录下的另外一个文件,文件名为: haha.txtFile destFile = new File(file.getParent(), "haha.txt");if (!destFile.exists()){if (destFile.createNewFile()){System.out.println("create success");}else {System.out.println("create error");}}
| public String getAbsolutePath() | 获取绝对路径 |
|---|---|
| public string getPath() | 获取路径 |
| public string getName() | 获取名称 |
| public string getParent() | 获取上层文件目录路径。若无,返回null |
| public long length() | 获取文件长度(即:字节数)。不能获取目录的长度。 |
| public long LastModified() | 获取最后一次的修改时间,毫秒值 |
如下的两个方法适用于文件目录:
| public String[ ] list() | 获取指定目录下的所有文件或者文件目录的名称数组 |
|---|---|
| public File[] listFiles() | 获取指定目录下的所有文件或者文件目录的File数组 |
| public boolean renameTo(File dest) | 把文件重命名为指定的文件路径 |
比如:file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
| public boolean isDirectory() | 判断是否是文件目录 |
|---|---|
| public boolean isFile() | 判断是否是文件 |
| public boolean exists() | 判断是否存在 |
| public boolean canRead() | 判断是否可读 |
| public boolean canWrite() | 判断是否可写 |
| public boolean isHidden() | 判断是否隐藏 |
创建硬盘中对应的文件或文件目录
| public boolean createNewFile() | 创建文件。若文件存在,则不创建,返回false |
|---|---|
| public boolean mkdir() | 创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录也不存在,也不创建。 |
| public boolean mkdirs() | 创建文件目录。如果上层文件目录不存在,一并创建 |
删除磁盘中的文件或文件目录
| public boolean delete() | 删除文件或者文件夹,要想删除目录成功,文件目录下不能有子目录或文件 |
|---|
删除注意事项:java中的删除不走回收站。
二、IO流
1.流的分类
- 操作数据单位:字节流、字符流
- 数据的流向:输入流、输出流
- 流的角色:节点流、处理流

2.流的体系结构
| 抽象基类 | 节点流(或文件流) | 缓冲流(处理流的一种) |
|---|---|---|
| InputStream | FileOutputStream—>read(byte[] buffer) | BufferedInputStream—>read(byte[] buffer) |
| OutputStream | FileInputStream–>write(byte[] buffer,0,len) | BufferedOutputStream–>write(byte[] buffer,0,len)/flush() |
| Reader | FileReader—>read(char[] cbuf) | BufferedReader—>read(char[] cbuf)/readLine() |
| Writer | FileWriter–>write(char[] cbuf,0,len) | BufferedWriter–>write(char[] cbuf,0,len)/flush() |
3.使用
字符流的使用
读文件
- read()的理解;返回读入的一个字符。如果达到文件末尾,返回-1
- 异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理
- 读入的文件一定要存在,否则就会报FileNotFoundException。
FileReader reader = null;try {//1.实例化File类的对象,指明要操作的文件File file = new File("hello.txt");//2.提供具体的流reader = new FileReader(file);//3.数据的读入//read():返回读入的一个字符。如果达到文件末尾,返回-1//方式一
// int data=reader.read();
// while (data!=-1){
// System.out.print((char) data);
// data=reader.read();
// }//方式二int data;while ((data=reader.read())!=-1){System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {//4.流的关闭操作try {assert reader != null;reader.close();} catch (IOException e) {e.printStackTrace();}}
使用read的重载方法
File file = new File("hello.txt");FileReader reader = null;try {reader = new FileReader(file);//read(char[] cbuf) 返回每次读入cbuf,数组中的字符的个数。如果达到文件末尾,返回-1char[] cbuffer=new char[5];int len;while ((len=reader.read(cbuffer))!=-1){
// for (int i = 0; i < len; i++) {
// System.out.print(cbuffer[i]);
// }System.out.print(new String(cbuffer,0,len));}} catch (IOException e) {e.printStackTrace();}
写文件
- 输出操作,对应的File可以不存在的。并不会报异常
- File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
File对应的硬盘中的文件如果存在:
----如果流使用的构造器是:FileWriter(file,false)/FileWriter(file):对原有文件的覆盖
----如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
//1.提供File类的对象,指明写出到的文件File file = new File("hello1.txt");FileWriter writer=null;try {//2.提供FileWriter的对象,用于数据的写出writer = new FileWriter(file,true);//3.写出的操作writer.write("I have a dream\n");writer.write("you need to have a dream");} catch (IOException e) {e.printStackTrace();}
//1.创建File类的对象,指明读入和写出的文件File srcFile = new File("hello.txt");File destFile = new File("hello2.txt");FileReader reader=null;FileWriter writer=null;//2.创建输入流和输出流的对象try {//不能使用字符流来处理图片等字节数据reader = new FileReader(srcFile);writer = new FileWriter(destFile);char[] cbuf=new char[5];int len;//记录每次读入到cbuf数组中的字符的个数//3.数据的读入和写出操作while ((len=reader.read(cbuf))!=-1){//每次写出len个字符writer.write(new String(cbuf,0,len));}} catch (IOException e) {e.printStackTrace();}
字节流的使用
指定路径下文件的复制
public void copyFile(String srcPath,String destPath){File srcFile = new File(srcPath);File destFile = new File(destPath);FileInputStream fis=null;FileOutputStream fos=null;try {fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);byte[] buffer = new byte[5];int len;while ((len=fis.read(buffer))!=-1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();}finally {if (fis!=null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}if (fos!=null){try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}
图片的复制
File srcFile = new File("abc.jpg");File destFile = new File("abcdef.jpg");FileInputStream fis=null;FileOutputStream fos=null;try {fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);byte[] buffer = new byte[5];int len;while ((len=fis.read(buffer))!=-1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();}
图片的加密
try {FileInputStream fis = new FileInputStream("abc.jpg");FileOutputStream fos = new FileOutputStream("a1b2c3.jpg");byte[] buffer = new byte[20];int len;while ((len=fis.read(buffer))!=-1){//字节数组进行修改for (int i = 0; i < buffer.length; i++) {buffer[i]= (byte) (buffer[i]^5);}fos.write(buffer);}} catch (IOException e) {e.printStackTrace();}
结论
- 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
- 对于非文本文件(图片,视频,音频),使用字节流处理
- 使用FileInputStream处理字符文件,可能出现乱码
处理流的使用
处理流,就是"套接”在己有的流的基础上.
转换流(属于字符流)
- InputStreamReader:将一个字节的输入流转换为字符的输入流
- OutputStreamWriter:将一个字符的输出流转换为字节的输出流
- 解码:字节、字节数组—>字符数组、字符串
- 编码:字符数组、字符串—>字节、字节数组
作用:提供字节流与字符流之间的转换
| ASCII | 美国标准信息交换码。用一个字节的7位可以表示。 |
|---|---|
| ISO8859-1 | 拉丁码表,欧洲码表.用一个字节的8位表示。 |
| GB2312 | 中国的中文编码表。最多两个字节编码所有字符 |
| GBK | 中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码 |
| Unicode | 国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。 |
| UTF-8 | 变长的编码方式,可用1-4个字节来表示一个字符。 |
File srcFile = new File("hello.txt");File destFile = new File("hello_gbk.txt");FileInputStream fis=null;FileOutputStream fos=null;InputStreamReader isr=null;OutputStreamWriter osw=null;try {fis= new FileInputStream(srcFile);fos= new FileOutputStream(destFile);isr = new InputStreamReader(fis, StandardCharsets.UTF_8);osw = new OutputStreamWriter(fos,"gbk");char[] cbuf = new char[20];int len;while ((len=isr.read(cbuf))!=-1){osw.write(cbuf,0,len);}System.out.println("success");} catch (IOException e) {e.printStackTrace();}
缓冲流
作用:提供流的读取、写入的速度
-------提高读写速度的原因:内部提供了一个缓冲区,默认8KB
实现非文本文件的复制
File srcFile = new File("abc.jpg");File destFile = new File("abcabc.jpg");FileInputStream fis;FileOutputStream fos;BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//节点流fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//缓冲流bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//读取,写入byte[] buffer = new byte[10];int len;while ((len=bis.read(buffer))!=-1){bos.write(buffer,0,len);
// bos.flush();//刷新缓冲区}} catch (IOException e) {e.printStackTrace();}
实现文本文件的复制
BufferedReader br=null;BufferedWriter bw=null;try {br=new BufferedReader(new FileReader(new File("hello.txt")));bw=new BufferedWriter(new FileWriter(new File("hello3.txt")));//方式一:使用char[]数组
// char[] buffer = new char[1024];
// int len;
// while ((len=br.read(buffer))!=-1){
// bw.write(buffer,0,len);
// }//方式二:使用StringString data;while ((data=br.readLine())!=null){bw.write(data);//data不包含换行符bw.newLine();}System.out.println("success");} catch (IOException e) {e.printStackTrace();}
要求
资源关闭先关闭外层的流,再关闭内层的流
说明
关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略
对象流
- ObjectInputStream 和ObjectOutputStream
- 作用:用于存储和读取基本数据类型数据或对象的处理流。
它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。 - 要想一个java对象是可序列化的,需要满足相应的要求。见Person.java
- 序列化机制:
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上, 或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
public class Person implements Serializable {public static final long serialVersionUID = 475463534532L;private String name;private int age;private Account account;public Account getAccount() {return account;}public void setAccount(Account account) {this.account = account;}public Person(String name, int age, Account account, int id) {this.name = name;this.age = age;this.account = account;this.id = id;}public int getId() {return id;}public void setId(int id) {this.id = id;}public Person(String name, int age, int id) {this.name = name;this.age = age;this.id = id;}private int id;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +", id=" + id +'}';}
}
class Account implements Serializable{public static final long serialVersionUID = 475469834532L;private double balance;public double getBalance() {return balance;}public void setBalance(double balance) {this.balance = balance;}public Account(double balance) {this.balance = balance;}@Overridepublic String toString() {return "Account{" +"balance=" + balance +'}';}
}
要求
- 需要实现接口: Serializable
- 当前类提供一个全局常量: serialVersionUID
- 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)
- 补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
序列化过程
将内存中的java对象保存到磁盘中或通过网络传输出去使用ObjectOutputStream实现
try {ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));oos.writeObject(new String("我爱山东"));oos.flush();oos.writeObject(new Person("王明",26));oos.flush();oos.writeObject(new Person("博古",27,new Account(5),9));oos.flush();} catch (IOException e) {e.printStackTrace();}
反序列化
将磁盘文件中的对象还原为内存中的一个java对象
try {ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));Object obj = ois.readObject();System.out.println(obj);Person p = (Person) ois.readObject();System.out.println(p);Person p1 = (Person) ois.readObject();System.out.println(p1);} catch (IOException | ClassNotFoundException e) {e.printStackTrace();}
其他流的使用
标准的输入、输出流
- System.in:标准的输入流,默认从键盘输入
- System.out:标准的输出流,默认从控制台输出
- System类的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定输入和输出
练习
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。
然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用system.in实现,system.in —>转换流—>BufferedReader的readline()
InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);while (true) {System.out.println("请输入字符串:");String data = br.readLine();if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {System.out.println("程序结束");break;}String upperCase = data.toUpperCase();System.out.println(upperCase);}
打印流
- PrintStream和PrintWriter
- 提供了一系列重载的print()和println()
PrintStream ps = null;try {FileOutputStream fos = new FileOutputStream(new File("D:\\text.txt"));//创建打印输出流,设置为自动刷新模式(写入换行符或字节‘\n’时都会刷新输出缓冲区)ps = new PrintStream(fos, true);//把标准输出流(控制台输出)改成文件System.setOut(ps);for (int i = 0; i <= 255; i++) { //输出ASCII字符System.out.print((char) i);if (i % 50 == 0) {//每5个数据一行System.out.println();} //换行}} catch (FileNotFoundException e) {e.printStackTrace();}
数据流
- DataInputStream 和DataOutputStream
- 作用:用于读取或写出基本数据类型的变量或字符串
- 注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
写出
try {DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));dos.writeUTF("姓名:?");dos.flush();//刷新操作,将内存中的数据写入文件dos.writeInt(25);dos.flush();dos.writeBoolean(false);dos.flush();} catch (IOException e) {e.printStackTrace();}
读取
try {DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));System.out.println(dis.readUTF());System.out.println(dis.readInt());System.out.println(dis.readBoolean());} catch (IOException e) {e.printStackTrace();}
4.RandomAccessFile
- RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
- RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
- 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建
-----------------------------------------------如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖) - 可以通过相关的操作,实现RandomAccessFile"插入"数据的效果
try {RandomAccessFile raf1 = new RandomAccessFile(new File("abc.jpg"),"r");RandomAccessFile raf2 = new RandomAccessFile(new File("abc01.jpg"),"rw");byte[] buffer = new byte[1024];int len;while ((len=raf1.read(buffer))!=-1){raf2.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();}
try {RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"),"rw");raf.seek(3);//将指针调到角标为3的位置raf.write("xyz".getBytes());} catch (IOException e) {e.printStackTrace();}
| r | 以只读方式打开 |
|---|---|
| rw | 打开以便读取和写入 |
| rwd | 打开以便读取和写入;同步文件内容的更新 |
| rws | 打开以便读取和写入;同步文件内容和元数据的更新 |
实现数据的插入
try {RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"),"rw");raf.seek(3);//将指针调到角标为3的位置byte[] buffer = new byte[20];//保存指针3后面的所有数据到StringBuilder中StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());int len;while ((len=raf.read(buffer))!=-1){builder.append(new String(buffer,0,len));}//调回指针,写入“xyz”raf.seek(3);raf.write("xyz".getBytes());//将StringBuilder中的数据写入到文件中raf.write(builder.toString().getBytes());//思考:将StringBuilder替换为ByteArrayOutputStream} catch (IOException e) {e.printStackTrace();}
三、网络编程
1.问题
- 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
- 找到主机后如何可靠高效地进行数据传输
2.IP和端口号
- IP:唯一的标识Internet 上的计算机(通信实体)
- 在ava中使用InetAddress类代表IP
- IP分类:IPv4和IPv6 ; 万维网和局域网
- 域名: www.baidu.com www.mi.com
- 本地回路地址:127.0.0.1对应着: Localhost
- 如何实例化InetAddress:两个方法: getByName(String host) , getLocalHost()
两个常用方法: getHostName() / getHostAddress() - 端口号:正在计算机上运行的进程。要求:不同的进程有不同的端口号
-范围:被规定为一个16位的整数0~65535。 - 8.端口号与IP地址的组合得出一个网络套接字:socket
try {InetAddress ia1 = InetAddress.getByName("192.168.1.100");System.out.println(ia1);InetAddress ia2 = InetAddress.getByName("www.baidu.com");System.out.println(ia2);InetAddress ia3 = InetAddress.getLocalHost();System.out.println(ia3);System.out.println(ia2.getHostName());System.out.println(ia2.getHostAddress());} catch (UnknownHostException e) {e.printStackTrace();}
3.网络通信协议
TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)

TCP
- 使用TCP协议前,须先建立TCP连接,形成传输数据通道
- 传输前,采用“三次握手”方式,点对点通信,是可靠的
- TCP协议进行通信的两个应用进程:客户端、服务端。
- 在连接中可进行大数据量的传输
- 传输完毕,需释放已建立的连接,效率低
练习一
客户端发送信息给服务端,服务端将数据显示在控制台上
客户端
- 创建Socket对象,指明服务器端的ip和端口号
- 获取一个输出流,用于输出数据
- 写出数据的操作
- 资源的关闭
Socket socket=null;OutputStream os=null;try {socket = new Socket(InetAddress.getByName("127.0.0.1"),654);os = socket.getOutputStream();os.write("你好,我是大铁人17号".getBytes());} catch (IOException e) {e.printStackTrace();}
服务端
- 创建服务器端的ServerSocket,指明自己的端口号
- 调用accept()表示接收来自于客户端的socket
- 获取输入流
- 读取输入流中的数据
ServerSocket ss=null;Socket socket=null;InputStream is=null;ByteArrayOutputStream baos = null;try {ss = new ServerSocket(654);socket = ss.accept();is = socket.getInputStream();//不建议这样写,可能会有乱码
// byte[] buffer = new byte[20];
// int len;
// while ((len=is.read(buffer))!=-1){
// System.out.println(new String(buffer, 0, len));
// }baos = new ByteArrayOutputStream();byte[] buffer = new byte[20];int len;while ((len=is.read(buffer))!=-1){baos.write(buffer,0,len);}System.out.println(baos.toString());} catch (IOException e) {e.printStackTrace();}
练习二
客户端发送文件给服务端,服务端将文件保存在本地。
客户端
Socket socket=null;OutputStream os=null;FileInputStream fis=null;try {socket = new Socket(InetAddress.getByName("127.0.0.1"), 664);os = socket.getOutputStream();fis = new FileInputStream("knife.jpg");byte[] buffer = new byte[1024];int len;while ((len=fis.read(buffer))!=-1){os.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();}
服务端
ServerSocket ss=null;Socket socket=null;try {ss = new ServerSocket(664);socket = ss.accept();InputStream is = socket.getInputStream();FileOutputStream fos = new FileOutputStream("zhan.jpg");byte[] buffer = new byte[1024];int len;while ((len=is.read(buffer))!=-1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();}
练习三
从客户端发送文件给服务端,服务端保存到本地。并返回"发送成功"给客户端。并关闭相应的连接。
客户端
Socket socket=null;OutputStream os=null;FileInputStream fis=null;InputStream is=null;ByteArrayOutputStream baos=null;try {socket = new Socket(InetAddress.getByName("127.0.0.1"), 664);os = socket.getOutputStream();fis = new FileInputStream("knife.jpg");byte[] buffer = new byte[1024];int len;while ((len=fis.read(buffer))!=-1){os.write(buffer,0,len);}//关闭数据的输出socket.shutdownOutput();//接收来自于服务器端的数据,并显示到控制台上is = socket.getInputStream();baos = new ByteArrayOutputStream();byte[] bytes = new byte[20];int length;while ((length=is.read(bytes))!=-1){baos.write(bytes,0,length);}System.out.println(baos.toString()+"???");} catch (IOException e) {e.printStackTrace();}
服务端
ServerSocket ss=null;Socket socket=null;InputStream is=null;FileOutputStream fos=null;OutputStream os=null;try {ss = new ServerSocket(664);socket = ss.accept();is = socket.getInputStream();fos = new FileOutputStream("zhan.jpg");byte[] buffer = new byte[1024];int len;while ((len=is.read(buffer))!=-1){fos.write(buffer,0,len);}System.out.println("传入完成 ");//服务器端给予客户端反馈os = socket.getOutputStream();os.write("照片已收到".getBytes());} catch (IOException e) {e.printStackTrace();}
UDP
- 将数据、源、目的封装成数据包,不需要建立连接
- 每个数据报的大小限制在64K内
- 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的>可以广播发送
- 发送数据结束时无需释放资源,开销小,速度快
- 不可靠;以数据报形式发送,数据报限定为64k;效率高
发送者
try {DatagramSocket ds = new DatagramSocket();String str="我是UDP发送的导弹";byte[] buffer = str.getBytes();InetAddress ia = InetAddress.getLocalHost();DatagramPacket dp = new DatagramPacket(buffer,buffer.length,ia,9782);ds.send(dp);} catch (IOException e) {e.printStackTrace();}
接收者
try {DatagramSocket ds = new DatagramSocket(9782);byte[] buffer = new byte[100];DatagramPacket dp = new DatagramPacket(buffer, 0, buffer.length);ds.receive(dp);System.out.println(new String(dp.getData(),0,dp.getLength()));} catch (IOException e) {e.printStackTrace();}
URL
统一资源定位符,对应着互联网的某一资源地址
| http | localhost | 8080 | exampLes/beauty.jpg | username=Tom |
|---|---|---|---|---|
| 协议 | 主机名 | 端口号 | 资源地址 | 参数列表 |
http://localhost:8080/exampLes/beauty.jpg?username=Tom
try {URL url = new URL("https://api.uomg.com/api/rand.qinghua?format=json");System.out.println(url.getProtocol());System.out.println(url.getHost());System.out.println(url.getPort());System.out.println(url.getPath());System.out.println(url.getFile());System.out.println(url.getQuery());} catch (MalformedURLException e) {e.printStackTrace();}
| public String getProtocol() | 获取该URL的协议名 |
|---|---|
| public String getHost() | 获取该URL的主机名 |
| public String getPort() | 获取该URL的端口号 |
| public String getPath() | 获取该URL的文件路径 |
| public String getFile() | 获取该URL的文件名 |
| public String getQuery() | 获取该URL的查询名 |
try {URL url = new URL("http://localhost:8080/test/jvav.png");HttpURLConnection uc = (HttpURLConnection) url.openConnection();uc.connect();InputStream is = uc.getInputStream();FileOutputStream fos = new FileOutputStream("jvav.png");byte[] buffer = new byte[1024];int len;while ((len=is.read(buffer))!=-1){fos.write(buffer,0,len);}uc.disconnect();System.out.println("success");} catch (IOException e) {e.printStackTrace();}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
