目录

  • 一、概述
  • 二、文件类(File)
    • 1. File类的构造、获取属性
    • 2. File类获取子文件或目录
    • 3. File类文件重命名
    • 4. File类的判断功能
    • 5. File类创建、删除功能
  • 三、I/O流
    • 1. 节点流(或文件流)
      • FileReader/FileWriter
        • 读取单个字符read()
        • 将字符读入数组read(char[] cbuf)
        • 从内存中写出数据到硬盘的文件里
        • 从一个文件读入并写出数据到另一个文件里
      • FileInputStream/FileOutputStream
        • 使用字节流FileInputStream处理文本文件
        • 实现对图片的复制操作
    • 2.缓冲流(处理流的一种)
      • 实现非文本文件的复制
      • 使用BufferedReader和BufferedWriter实现文本文件的复制
    • 3.转换流(处理流的一种)
      • 设置读取时的字符集
      • 以指定的字符集写入
    • 3.其他流
      • 标准的输入、输出流
      • 打印流:PrintStream 和PrintWriter
      • 数据流
      • 对象流
      • 随机存取文件流
  • 四、网络编程(TCP/UDP)
    • 1.InetAddress
    • 2.实现TCP的网络编程
    • 3.UDP协议的网络编程
    • 4.URL网络编程
  • 五、总结

一、概述

Java.io 包几乎包含了所有操作输入、输出需要的类。所有这些流类代表了输入源和输出目标。
Java.io 包中的流支持很多种格式,比如:基本类型、对象、本地化字符集等等。
一个流可以理解为一个数据的序列。输入流表示从一个源读取数据,输出流表示向一个目标写数据。
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。
但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。

二、文件类(File)

  1. java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关。
  2. File 能新建、删除、重命名文件和目录,但File不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
  3. 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
  4. File对象可以作为参数传递给流的构造器。

1. File类的构造、获取属性

public class Main02 {public static void main(String[] args) {//构造器1File file1 = new File("hello.txt");//相对于当前moduleFile file2 = new File("D:\\he.txt");//文件系统中不存在这个文件System.out.println(file1);//hello.txtSystem.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.txtSystem.out.println(file1.getAbsolutePath());//E:\Users\16931\IdeaProjects\HelloWorld\hello.txtSystem.out.println(file1.getPath());//hello.txtSystem.out.println(file1.getName());//hello.txtSystem.out.println(file1.getParent());//nullSystem.out.println(file1.length());//3System.out.println(new Date(file1.lastModified()));//Fri Apr 29 22:25:33 CST 2022System.out.println();System.out.println(file2.getAbsolutePath());//D:\he.txtSystem.out.println(file2.getPath());//D:\he.txtSystem.out.println(file2.getName());//he.txtSystem.out.println(file2.getParent());//D:\System.out.println(file2.length());//0System.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类创建、删除功能

删除注意事项:

  1. Java中的删除不走回收站。
  2. 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
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流

  1. I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。
  2. Java程序中,对于数据的输入/输出操作以“流(stream)” 的 方式进行。
  3. java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
(抽象基类) 字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer
  1. Java的IO流共涉及40多个类,实际上非常规则,都是从如下4个 抽象基类派生的。
  2. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

程序中打开的文件 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():返回读入的一个字符。如果达到文件末尾,返回-1int 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数组中的字符的个数。如果达到文件末尾,返回-1char[] 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();}}}}
}

从内存中写出数据到硬盘的文件里

说明:

  1. 输出操作,对应的File可以不存在的。并不会报异常
  2. 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();}}}}
}
  1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

2.缓冲流(处理流的一种)

  1. 缓冲流:BufferedInputStream、BufferedOutputStream、BufferedReader、BufferedWriter
  2. 作用:提供流的读取、写入的速度。提高读写速度的原因:内部提供了一个缓冲区
  3. 处理流,就是“套接”在已有的流的基础上。

实现非文本文件的复制

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.转换流(处理流的一种)

  1. 转换流:属于字符流。nputStreamReader:将一个字节的输入流转换为字符的输入流。OutputStreamWriter:将一个字符的输出流转换为字节的输出流
  2. 作用:提供字节流与字符流之间的转换
  3. 解码:字节、字节数组 —>字符数组、字符串;编码:字符数组、字符串 —> 字节、字节数组

设置读取时的字符集

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();}
}

对象流

  1. ObjectInputStream 和 ObjectOutputStream
  2. 作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
  3. 要想一个java对象是可序列化的,需要满足相应的要求。
  1. 序列化机制:
    对象序列化机制允许把内存中的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;}@Overridepublic 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;@Overridepublic 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的使用

  1. RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
  2. RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
  3. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
    如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
  4. 可以通过相关的操作,实现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)

一、 网络编程中有两个主要的问题:

  1. 如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
  2. 找到主机后如何可靠高效地进行数据传输
    二、网络编程中的两个要素:
  3. 对应问题一:IP和端口号
  4. 对应问题二:提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、物理+数据链路层)
    三、通信要素一:IP和端口号
  5. IP:唯一的标识 Internet 上的计算机(通信实体)
  6. 在Java中使用InetAddress类代表IP
  7. IP分类:IPv4 和 IPv6 ; 万维网 和 局域网
  8. 域名: www.baidu.com www.mi.com www.sina.com www.jd.com
  9. 本地回路地址:127.0.0.1 对应着:localhost
  10. 如何实例化InetAddress:两个方法:getByName(String host) 、 getLocalHost()
    两个常用方法:getHostName() / getHostAddress()
  11. 端口号:正在计算机上运行的进程。
    要求:不同的进程有不同的端口号
    范围:被规定为一个 16 位的整数 0~65535。
  12. 端口号与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.14InetAddress inet2 = InetAddress.getByName("www.baidu.com");System.out.println(inet2);//www.baidu.com/183.232.231.174InetAddress inet3 = InetAddress.getByName("127.0.0.1");System.out.println(inet3);///127.0.0.1InetAddress inet4 = InetAddress.getLocalHost();System.out.println(inet4);//PC/192.168.111.1System.out.println(inet2.getHostName());//www.baidu.comSystem.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网络编程

  1. URL:统一资源定位符,对应着互联网的某一资源地址
  2. 格式:
    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流以及网络编程做了简要说明。限于篇幅和个人水平,未能详尽介绍全部内容。以上是基础介绍,适合刚入门的同学参考。

Java的IO流与网络编程相关推荐

  1. JAVA的IO流 和网络编程 超详细每行代码都有备注

    IO流: {     文件的操作: f1.getAbsolutePath();//获取绝对路径               f1.getPath();//获取相对路径               f1 ...

  2. Java的IO模型基于网络编程利弊分析

    JAVA的IO模型基于网络编程利弊分析 一.IO通俗理解 IO的过程 思考①答案:文件句柄 思考②答案: 阻塞/非阻塞 IO(程序对内核空间数据拷贝到用户空间阶段的耗时操作的等待方式) 同步/异步IO ...

  3. java基础知识总结:基础知识、面向对象、集合框架、多线程、jdk1.5新特性、IO流、网络编程

    目录 一.基础知识: 二.面向对象 三.集合框架 四.多线程: 五.jdk1.5的新特性 六.IO流 七.网络编程: 一.基础知识: 1.JVM.JRE和JDK的区别: JVM(Java Virtua ...

  4. 泛型、IO流 和 网络编程

    文章目录

  5. 【Java网络编程与IO流】Java中IO流分为几种?字符流、字节流、缓冲流、输入流、输出流、节点流、处理流

    Java网络编程与IO流目录: [Java网络编程与IO流]Java中IO流分为几种?字符流.字节流.缓冲流.输入流.输出流.节点流.处理流 [Java网络编程与IO流]计算机网络常见面试题高频核心考 ...

  6. java基础 io流 字节流 字符流 节点流 包装流 转换流 缓冲流 对象流 打印流 Properties类

    目录 1.概念 2.常用的文件操作 2.1 创建文件 2.2 获取文件相关信息 2.3 目录的操作和文件删除 3. IO流原理及流的分类 3.1 流的分类 4.InputStream 字节输入流 4. ...

  7. Java入门——IO流

    一.File类的使用 1.1 File类的实例化 java.io.File类:文件和文件目录路径的抽象表示形式,与平台无关 File 能新建.删除.重命名文件和目录,但File 不能访问文件内容本身. ...

  8. # Java基础——IO流

    Java基础--IO流 File类的使用(熟悉构造器和方法的使用) File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹) File类的声明在java.io包下 文件和文件目录路径的抽象表示 ...

  9. java数据通道抽象为流_【java】IO流

    对于java的IO流的理解很长时间来都是很乱,包括学习其他的语言对这一块知识也都算是一个盲点.更多的时候一提到读取保存数据就是使用数据库.这一次学习了IO流,自己又解决了一个很大的盲点. IO流为我们 ...

最新文章

  1. Xamarin 学习笔记 - 配置环境(Windows iOS)
  2. Ubuntu中Netbeans的中文问题彻底解决
  3. 趣味编程:函数式链表的快速排序
  4. windows10 系统设置一键备份
  5. 用Python3Request爬取英雄联盟皮肤、单线程爬取
  6. 工业视觉镜头NAVITAR
  7. 【音视频安卓开发 (八)】OpenSLES播放音频步骤和接口讲解
  8. 生日快乐!中国航天员“天团”
  9. Objective-C 2.0 with Cocoa Foundation--- 7,对象的初始化以及实例变量的作用域
  10. Spark : ExitCodeException exitCode=15,exitCode=13
  11. 搜狐畅游笔试题:1. 美丽的项链(动态规划) 2.多线程并发交替输出
  12. 随想录(cuda编程)
  13. APUE 线程的分离状态
  14. spring boot面试_Spring Boot面试问题
  15. Javascript:利用闭包实现高级排他
  16. 中缀表达式转化成后缀表达式
  17. 谈谈BFC与ie特有属性hasLayout
  18. 重磅开源!一款引入实时语音与声纹识别的网络辩论系统!
  19. U3D游戏开发效率和UE4相比哪个高?
  20. 设计的概念以及含义_什么是设计概念? 以及为什么您应该始终从一个开始

热门文章

  1. [读书笔记] 自然语言处理中的损失函数和正则项
  2. 首款7nm手机芯片麒麟980发布 华为Mate20系列率先搭载全球首发
  3. 一文详解DeepID-Net
  4. 安卓面试易考题(五)
  5. rtx 2080s和rtx2070s 参数对比 性能差多少
  6. 华为鸿蒙P30,华为Mate 30 Lite曝光 或搭载鸿蒙OS9月上市
  7. latex使用IEEE trans模板时插入png pdf等格式的图片
  8. 怎样解决word自动编号出现内容空格过大的问题即表号和标题间的空格
  9. 电视剧《婚姻保卫战》经典语录整理
  10. sftp工具都有哪些_建站工具篇:在首次建站过程中,我都用到了哪些建站工具?...