一、概述
Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。
Java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。
一个流可以理解为一个数据的序列。输入流表示从一个源读取数据,输出流表示向一个目标写数据。
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。
但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
二、文件类(File)
- java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关。
- File 能新建、删除、重命名文件和目录,但File不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
- 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
- File对象可以作为参数传递给流的构造器。
1. File类的构造、获取属性
public class Main02 {
public static void main(String[] args) {
//构造器1
File file1 = new File("hello.txt");//相对于当前module
File file2 = new File("D:\\he.txt");//文件系统中不存在这个文件
System.out.println(file1);//hello.txt
System.out.println(file2);//D:\he.txt
//构造器2:
File file3 = new File("D:\\hello", "abc");
System.out.println(file3);//D:\hello\abc
//构造器3:
File file4 = new File(file3, "hi.txt");
System.out.println(file4);//D:\hello\abc\hi.txt
System.out.println(file1.getAbsolutePath());//E:\Users\16931\IdeaProjects\HelloWorld\hello.txt
System.out.println(file1.getPath());//hello.txt
System.out.println(file1.getName());//hello.txt
System.out.println(file1.getParent());//null
System.out.println(file1.length());//3
System.out.println(new Date(file1.lastModified()));//Fri Apr 29 22:25:33 CST 2022
System.out.println();
System.out.println(file2.getAbsolutePath());//D:\he.txt
System.out.println(file2.getPath());//D:\he.txt
System.out.println(file2.getName());//he.txt
System.out.println(file2.getParent());//D:\
System.out.println(file2.length());//0
System.out.println(file2.lastModified());//0
}
}
2. File类获取子文件或目录
public class Main02 {
public static void main(String[] args) {
File file = new File("D:\\Users");
String[] list = file.list();
for (String s : list) {
System.out.println(s);//16931
}
System.out.println();
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f);//D:\Users\16931
}
}
}
3. File类文件重命名
public class Main02 {
public static void main(String[] args) {
File file1 = new File("hello.txt");
File file2 = new File("D:\\he.txt");
boolean renameTo = file1.renameTo(file2);//要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
System.out.println(renameTo);
}
}
4. File类的判断功能
public class Main02 {
public static void main(String[] args) {
File file1 = new File("hello.txt");
System.out.println(file1.isDirectory());
System.out.println(file1.isFile());
System.out.println(file1.exists());
System.out.println(file1.canRead());
System.out.println(file1.canWrite());
System.out.println(file1.isHidden());
System.out.println();
File file2 = new File("d:\\Users");
System.out.println(file2.isDirectory());
System.out.println(file2.isFile());
System.out.println(file2.exists());
System.out.println(file2.canRead());
System.out.println(file2.canWrite());
System.out.println(file2.isHidden());
}
}
5. File类创建、删除功能
删除注意事项:
- Java中的删除不走回收站。
- 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
public class Main02 {
public static void main(String[] args) throws IOException {
File file1 = new File("hi.txt");
if (!file1.exists()) {
//文件的创建
file1.createNewFile();
System.out.println("创建成功");
} else {//文件存在
file1.delete();
System.out.println("删除成功");
}
//文件目录的创建
File file = new File("d:\\io\\io1\\io3");
boolean mkdir = file.mkdir();
if (mkdir) {
System.out.println("创建成功1");
}
File file2 = new File("d:\\io\\io1\\io4");
boolean mkdir1 = file2.mkdirs();
if (mkdir1) {
System.out.println("创建成功2");
}
//要想删除成功,io4文件目录下不能有子目录或文件
File file3 = new File("D:\\io\\io1\\io4");
System.out.println(file3.delete());
}
}
三、I/O流
- I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
- Java程序中,对于数据的输入/输出操作以“流(stream)” 的 方式进行。
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
- Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个 抽象基类派生的。
- 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
程序中打开的文件 IO 资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件 IO 资源。
分类 | 字节输入流 | 字节输出流 | 字符输入流 | 字符输出流 |
---|---|---|---|---|
抽象基类 | InputStream | OutputStream | Reader | Writer |
访问文件 | FileInputStream | FileOutputStream | FileReader | FileWriter |
访问数组 | ByteArrayInputStream | ByteArrayOutputStream | CharArrayReader | CharArrayWriter |
访问管道 | PipedInputStream | PipedOutputStream | PipedReader | PipedWriter |
访问字符串 | StringReader | StringWriter | ||
缓冲流 | BufferedInputStream | BufferedOutputStream | BufferedReader | BufferedWriter |
转换流 | InputStreamReader | OutputStreamWriter | ||
对象流 | ObjectInputStream | ObjectOutputStream | ||
FilterInputStream | FilterOutputStream | FilterReader | FilterWriter | |
打印流 | PrintStream | PrintWriter | ||
推回输入流 | PushbackInputStream | PushbackReader | ||
特殊流 | DataInputStream | DataOutputStream |
1. 节点流(或文件流)
FileReader/FileWriter
读取单个字符read()
public class Main02 {
public static void main(String[] args) throws IOException {
FileReader fr = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前Module
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read():返回读入的一个字符。如果达到文件末尾,返回-1
int data;
while ((data = fr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭操作
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
将字符读入数组read(char[] cbuf)
public class Main02 {
public static void main(String[] args) throws IOException {
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
//4.资源的关闭
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
从内存中写出数据到硬盘的文件里
说明:
- 输出操作,对应的File可以不存在的。并不会报异常
- File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
File对应的硬盘中的文件如果存在:
如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
public class Main02 {
public static void main(String[] args) throws IOException {
FileWriter fw = null;
try {
//1.提供File类的对象,指明写出到的文件
File file = new File("hello1.txt");
//2.提供FileWriter的对象,用于数据的写出
fw = new FileWriter(file, false);
//3.写出的操作
fw.write("I have a dream!\n");
fw.write("you need to have a dream!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流资源的关闭
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
从一个文件读入并写出数据到另一个文件里
public class Main02 {
public static void main(String[] args) throws IOException {
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.txt");
//不能使用字符流来处理图片等字节数据
// File srcFile = new File("爱情与友情.jpg");
// File destFile = new File("爱情与友情1.jpg");
//2.创建输入流和输出流的对象
fr = new FileReader(srcFile);
fw = new FileWriter(destFile);
//3.数据的读入和写出操作
char[] cbuf = new char[5];
int len;//记录每次读入到cbuf数组中的字符的个数
while ((len = fr.read(cbuf)) != -1) {
//每次写出len个字符
fw.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流资源
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileInputStream/FileOutputStream
使用字节流FileInputStream处理文本文件
public class Main02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
try {
//1. 造文件。文本中的中文可能出现乱码。
File file = new File("hello.txt");
//2.造流
fis = new FileInputStream(file);
//3.读数据
byte[] buffer = new byte[5];
int len;//记录每次读取的字节的个数
while ((len = fis.read(buffer)) != -1) {
String str = new String(buffer, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
//4.关闭资源
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
实现对图片的复制操作
public class Main02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
File srcFile = new File("爱情与友情.jpg");
File destFile = new File("爱情与友情2.jpg");
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 (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
- 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
2.缓冲流(处理流的一种)
- 缓冲流:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter
- 作用:提供流的读取、写入的速度。提高读写速度的原因:内部提供了一个缓冲区
- 处理流,就是“套接”在已有的流的基础上。
实现非文本文件的复制
public class Main02 {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("爱情与友情.jpg");
File destFile = new File("爱情与友情3.jpg");
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream((srcFile));
FileOutputStream fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
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();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
//fos.close();
//fis.close();
}
}
}
使用BufferedReader和BufferedWriter实现文本文件的复制
public class Main02 {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
//创建文件和相应的流
br = new BufferedReader(new FileReader(new File("dbcp.txt")));
bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
String data;
while ((data = br.readLine()) != null) {
bw.write(data);//data中不包含换行符
bw.newLine();//提供换行的操作
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.转换流(处理流的一种)
- 转换流:属于字符流。nputStreamReader:将一个字节的输入流转换为字符的输入流。OutputStreamWriter:将一个字符的输出流转换为字节的输出流
- 作用:提供字节流与字符流之间的转换
- 解码:字节、字节数组 —>字符数组、字符串;编码:字符数组、字符串 —> 字节、字节数组
设置读取时的字符集
public class Main02 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("dbcp.txt");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
//参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");//使用UTF-8字符集
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
String str = new String(cbuf, 0, len);
System.out.print(str);
}
isr.close();
}
}
以指定的字符集写入
public class Main02 {
public static void main(String[] args) throws IOException {
File file1 = new File("dbcp.txt");
File file2 = new File("dbcp_gbk.txt");
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
InputStreamReader isr = new InputStreamReader(fis, "utf-8");
OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");
char[] cbuf = new char[20];
int len;
while ((len = isr.read(cbuf)) != -1) {
osw.write(cbuf, 0, len);
}
isr.close();
osw.close();
}
}
3.其他流
标准的输入、输出流
public class Main02 {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
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);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
打印流:PrintStream 和PrintWriter
public class Main02 {
public static void main(String[] args) throws IOException {
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("IOtext.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
ps = new PrintStream(fos, true);
if (ps != null) {// 把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) { // 输出ASCII字符
System.out.print((char) i);
if (i % 50 == 0) { // 每50个数据一行
System.out.println(); // 换行
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
}
}
}
数据流
DataInputStream 和 DataOutputStream
作用:用于读取或写出基本数据类型的变量或字符串
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
public class Main02 {
public static void main(String[] args) throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("刘建辰");
dos.flush();//刷新操作,将内存中的数据写入文件
dos.writeInt(23);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name = " + name);
System.out.println("age = " + age);
System.out.println("isMale = " + isMale);
dis.close();
}
}
对象流
- ObjectInputStream 和 ObjectOutputStream
- 作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
- 要想一个java对象是可序列化的,需要满足相应的要求。
- 序列化机制:
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种
二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
当其它程序获取了这种二进制流,就可以恢复成原来的Java对象。
/**
* Person需要满足如下的要求,方可序列化
* 1.需要实现接口:Serializable
* 2.当前类提供一个全局常量:serialVersionUID
* 3.除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性
* 也必须是可序列化的。(默认情况下,基本数据类型可序列化)
* 补充:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
*/
public class Person implements Serializable {
public static final long serialVersionUID = 475463534532L;
private String name;
private int age;
private int id;
private Account acct;
public Person(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public Person(String name, int age, int id, Account acct) {
this.name = name;
this.age = age;
this.id = id;
this.acct = acct;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
", acct=" + acct +
'}';
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
}
class Account implements Serializable {
public static final long serialVersionUID = 4754534532L;
private double balance;
@Override
public String toString() {
return "Account{" +
"balance=" + balance +
'}';
}
public Account(double balance) {
this.balance = balance;
}
}
public class Main02 {
public static void main(String[] args) throws IOException {
//序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱北京天安门"));
oos.flush();//刷新操作
oos.writeObject(new Person("王铭", 23));
oos.flush();
oos.writeObject(new Person("张学良", 23, 1001, new Account(5000)));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化:将磁盘文件中的对象还原为内存中的一个java对象
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String) obj;
Person p = (Person) ois.readObject();
Person p1 = (Person) ois.readObject();
System.out.println(str);
System.out.println(p);
System.out.println(p1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
随机存取文件流
RandomAccessFile的使用
- RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
- RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
- 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖) - 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
public class Main02 {
//使用RandomAccessFile实现数据的插入效果
public static void main(String[] args) throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("hello.txt", "rw");
raf1.seek(3);//将指针调到角标为3的位置
//保存指针3后面的所有数据到StringBuilder中
StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
byte[] buffer = new byte[20];
int len;
while ((len = raf1.read(buffer)) != -1) {
builder.append(new String(buffer, 0, len));
}
//调回指针,写入“xyz”
raf1.seek(3);
raf1.write("xyz".getBytes());
//将StringBuilder中的数据写入到文件中
raf1.write(builder.toString().getBytes());
raf1.close();
}
}
Java NIO (New IO,Non-Blocking IO)是从Java 1.4版本开始引入的一套新的IO API,可以替代标准的Java IO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓区的(IO是面向流的)、基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。
四、网络编程(TCP/UDP)
一、 网络编程中有两个主要的问题:
- 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
- 找到主机后如何可靠高效地进行数据传输
二、网络编程中的两个要素: - 对应问题一:IP和端口号
- 对应问题二:提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)
三、通信要素一:IP和端口号 - IP:唯一的标识 Internet 上的计算机(通信实体)
- 在Java中使用InetAddress类代表IP
- IP分类:IPv4 和 IPv6 ; 万维网 和 局域网
- 域名: www.baidu.com www.mi.com www.sina.com www.jd.com
- 本地回路地址:127.0.0.1 对应着:localhost
- 如何实例化InetAddress:两个方法:getByName(String host) 、 getLocalHost()
两个常用方法:getHostName() / getHostAddress() - 端口号:正在计算机上运行的进程。
要求:不同的进程有不同的端口号
范围:被规定为一个 16 位的整数 0~65535。 - 端口号与IP地址的组合得出一个网络套接字:Socket
1.InetAddress
public class Main02 {
public static void main(String[] args) throws IOException {
try {
InetAddress inet1 = InetAddress.getByName("192.168.10.14");
System.out.println(inet1);///192.168.10.14
InetAddress inet2 = InetAddress.getByName("www.baidu.com");
System.out.println(inet2);//www.baidu.com/183.232.231.174
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
System.out.println(inet3);///127.0.0.1
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet4);//PC/192.168.111.1
System.out.println(inet2.getHostName());//www.baidu.com
System.out.println(inet2.getHostAddress());//183.232.231.174
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
2.实现TCP的网络编程
public class Main02 {
public static void main(String[] args) throws IOException {
new Thread(() -> {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
OutputStream os = null;
try {
ss = new ServerSocket(9090);
socket = ss.accept();
is = socket.getInputStream();
fos = new FileOutputStream(new File("beauty2.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("图片传输完成");
//6.服务器端给予客户端反馈
os = socket.getOutputStream();
os.write("你好,美女,照片我已收到,非常漂亮!".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "server").start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
FileInputStream fis = null;
OutputStream os = null;
Socket socket = null;
ByteArrayOutputStream baos = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
os = socket.getOutputStream();
fis = new FileInputStream(new File("beauty.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
//关闭数据的输出
socket.shutdownOutput();
//5.接收来自于服务器端的数据,并显示到控制台上
InputStream is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bufferr = new byte[20];
int len1;
while ((len1 = is.read(buffer)) != -1) {
baos.write(buffer, 0, len1);
}
System.out.println(baos.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}, "client").start();
}
}
此处创建了两个线程,一个模拟客户端,一个模拟服务端。写法使用了Lambda表达式。
相关参考:
Lambda表达式的用法(函数式接口、方法引用)
Java并发编程(JUC)
3.UDP协议的网络编程
public class Main02 {
public static void main(String[] args) throws IOException {
new Thread(() -> {
try {
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), 0, packet.getLength()));
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}, "server").start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
try {
DatagramSocket socket = null;
socket = new DatagramSocket();
String str = "我是UDP方式发送的导弹";
byte[] data = str.getBytes();
InetAddress inet = null;
inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 9090);
socket.send(packet);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}, "client").start();
}
}
4.URL网络编程
- URL:统一资源定位符,对应着互联网的某一资源地址
- 格式:
http://localhost:8080/examples/beauty.jpg?username=Tom
协议 主机名 端口号 资源地址 参数列表
public class Main02 {
public static void main(String[] args) throws IOException {
HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL("https://img-blog.csdnimg.cn/9cf9deb2b48d40408f2dff5dc096c5ff.png");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("beauty3.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("下载完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
}
通过URL能直接下载网站的文件到本地
五、总结
本文对IO流以及网络编程做了简要说明。限于篇幅和个人水平,未能详尽介绍全部内容。以上是基础介绍,适合刚入门的同学参考。