java.io.File类:文件和文件目录路径的抽象表示,与平台无关。
File能新建,删除,重命名文件和目录,但File不能访问文件内容本身,如果需要访问文件内容,则需要使用输入/输出流。
想要在Java程序中表示一个真实存在的的文件或目录,那么必须有一个File对象,但Java中的一个File对象,可能没有一个真实存在的文件或目录。
File对象可以作为参数传递给流的构造器。
创建File类的实例路径分割符:windows:\;unix:/
三种构造器:
File(String filePath)
File(String parentPath,String childPath)
File(File ParentFile,String childPath)
@Test
public void test() {
//相对路径
File file1 = new File("test.txt");
//绝对路径
File file2 = new File("D:\ideaworkspace\Spring\base\test.txt");
//可以用separator代替路径分隔符 不同操作系统适配
File file3 = new File("D:" + File.separator + "ideaworkspace" + File.separator
+ "Spring" + File.separator + "base" + File.separator + "test.txt");
System.out.println(file3);
//构造器2
File file4 = new File("D:\ideaworkspace", "Spring");
System.out.println(file4);
//构造器3
File file5 = new File(file4, "test.txt");
System.out.println(file5);
}
File类的常用方法
@Test
public void test() throws IOException {
//相对路径
File file1 = new File("test.txt");
//绝对路径
File file2 = new File("D:\ideaworkspace\Spring");
//获取文件绝对路径
System.out.println(file1.getAbsolutePath());
//获取路径
System.out.println(file1.getPath());
//获取名称
System.out.println(file1.getName());
//获取上层文件目录路径,若无返回null 相对路径
System.out.println(file1.getParent());
//获取文件长度,字节数
System.out.println(file1.length());
//获取最后一次修改时间
System.out.println(file1.lastModified());
//获取指定目录下所有文件或者文件目录的名称数组
String[] list = file2.list();
for (String s : list) {
System.out.print(s + "t");
}
System.out.println();
//获取指定目录下所有文件或者文件目录的文件数组
File[] files = file2.listFiles();
for (File file : files) {
System.out.print(file.getName() + "t");
}
System.out.println();
//把文件重命名为指定的文件路径
//需要保证file1在硬盘中存在,参数中file3不存在
//先当与更改文件位置和文件名称为file3
File file3 = new File("a.txt");
boolean renameTo = file1.renameTo(file3);
System.out.println(renameTo);
//判断是不是目录
boolean isDirectory = file3.isDirectory();
System.out.println(isDirectory);
//判断是不是文件
boolean isFile = file3.isFile();
System.out.println(isFile);
//判断是否存在
boolean exists = file3.exists();
System.out.println(exists);
//判断是否可读,可写
boolean canRead = file3.canRead();
boolean canWrite = file3.canWrite();
System.out.println(canRead);
System.out.println(canWrite);
//判断是否隐藏
boolean isHidden = file3.isHidden();
System.out.println(isHidden);
//创建文件,若已存在则不创建
File file4 = new File("test.txt");
if (!file4.exists()) {
file4.createNewFile();
System.out.println("创建成功");
} else {
//删除文件
file4.delete();
System.out.println("删除成功");
}
//创建文件目录,若已存在或此文件上次目录不存在则不创建
File file5 = new File("NOTEXIT/test");
boolean mkdir = file5.mkdir();
System.out.println(mkdir);
//创建文件目录,若文件上层目录不存在一并创建
boolean mkdirs = file5.mkdirs();
System.out.println(mkdirs);
}
IO流
I/O是Input和OutPut的缩写,I/O是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通询等。
Java程序中,对于数据的输入/输出操作以"流(Stream)"的方式进行。
Java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
流的分类按操作数据单位不同分为:
字节流(8 bit):处理图片视频等非文本文件(.jpg .mp3 .mp4 .avi .doc .ppt ……)
字符流(16 bit):文本文件(.txt .java .c .cpp)。用字节流复制文本文件也不会出错,只是在内存中输出可能会乱码
按数据流的流向不同分为:输入流,输出流
按流的角色的不同分为:节点流,处理流
IO流体系
抽象基类 文件流(节点流的一种) 缓冲流(处理流的一种)
InputStream FileInputStream BufferedInputStreamr
OutputStream FileOutputStream BufferedOutputStream
Reader FileReader BufferedReader
Writer FileWriter BufferedWriter
文件流 FileReader读入数据的基本操作public class TestIO {
@Test
public void test() {
//实例化File类的对象,指明要操作的文件
//如果是在main方法中表示当前工程下的a.txt,这里是module下的
File file = new File("a.txt");
FileReader fr = null;
try {
//提供具体的流 可能会出现FileNotFoundException
fr = new FileReader(file);
//数据的读入
//read()
// 方式一
// int data = fr.read();//返回读入的一个字符到末尾返回-1
// while (data != -1) {
// System.out.print((char) data);
// //读取下一个字符
// data = fr.read();
// }
//方式二
// int data;
// while ((data = fr.read()) != -1) {
// System.out.print((char) data);
// }
//read(char[] cbuf) 返回每次读入到cbuf数组中字符个数,末尾-1
//每次读入覆盖上次读入的内容,长度不足时保留前一次的内容
char[] cbuf = new char[5];
int len;
while ((len = fr.read(cbuf)) != -1) {
//方式一
// for (int i = 0; i < len; i++) {
// System.out.print(cbuf[i]);
// }
//方式二
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
//判断流是否实例化成功
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileWriter写出数据的操作
public class TestIO {
@Test
public void test() {
//提供File类的对象,指明写出到的文件。
File file = new File("write.txt");
FileWriter fw = null;
try {
//提供FileWriter的对象,用于数据的写出
//写入时文件不存在自动创建
//存在且使用FileWriter(file)/FileWriter(file,false)则覆盖
//文件存在且使用FileWriter(file,true)构造器则不覆盖,在原文件添加
fw = new FileWriter(file, true);
fw.write("写进去了吗?n");
fw.write("写进去了啊!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//实现文件复制 a.txt -> write.txt
@Test
public void test2() {
//创建File类的对象,指明读入和写出的文件
File file1 = new File("a.txt");
File file2 = new File("write.txt");
//提供流对象
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(file1);
fw = new FileWriter(file2);
//读入并写出数据
char[] cubf = new char[5];
//记录每次读入到cbuf数组中的字符个数
int len;
while ((len = fr.read(cubf)) != -1) {
//向文件中写入len个字符
fw.write(cubf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileInputStream和FileOutputStream
操作非文本数据,实现对非文本文件的复制
public class TestIO {
@Test
public void test() {
//创建文件对象
File srcfile = new File("1.jpg");
File destfile = new File("2.jpg");
//创建流
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
//读数据
byte[] b = new byte[10];
int len;
while ((len = fis.read(b)) != -1) {
//写数据
fos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//对其进一步封装
@Test
public void test2() {
Template t1 = new Template() {
@Override
public void function() {
CopyFile("D:\mp3\1.mp3", "D:\mp3\2.mp3");
}
};
t1.spendTime();
}
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[] b = new byte[10];
int len;
while ((len = fis.read(b)) != -1) {
//写数据
fos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
abstract class Template {
public void spendTime() {
long start = System.currentTimeMillis();
function();
long end = System.currentTimeMillis();
System.out.println("花费时间为:" + (end - start) + "ms");
}
abstract void function();
}
缓冲流
BufferedInputStream/BufferedOutPutStream
处理流,就是“套接"在已有的流的基础上的流
非文本文件复制
public class TestIO {
@Test
public void test() {
Template t1 = new Template() {
@Override
public void function() {
CopyFile("D:\mp3\1.mp3", "D:\mp3\2.mp3");
}
};
t1.spendTime();
}
public void CopyFile(String srcPath, String destPath) {
//创建文件
File srcfile = new File(srcPath);
File destfile = new File(destPath);
//创建流
FileInputStream fis = null;
FileOutputStream fos = null;
//创建缓冲流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//读数据
byte[] b = new byte[10];
int len;
while ((len = bis.read(b)) != -1) {
//写数据
bos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
//要求:先关闭外层的流,再关闭内层的流
//关闭外层流时会自动关闭内层流,所以只关外层即可
try {
if (bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (bis != null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
abstract class Template {
public void spendTime() {
long start = System.currentTimeMillis();
function();
long end = System.currentTimeMillis();
System.out.println("花费时间为:" + (end - start) + "ms");
}
abstract void function();
}
由上文两次代码结果可以看出复制相同的文件文件流和缓冲流的速度对比明显缓冲流更快
作用:提高流的读取,写入的速度
原因:内部提供了一个缓冲区,先把写入的数据存放到缓冲区,当数据大于默认缓冲区容量(8192字节)时,会自动调用flush方法将缓冲区内容一次性写入。也可以自行调用flush方法
BufferedReader/BufferedWiterpublic class TestIO {
@Test
public void test() {
//创建文件
File file1 = new File("a.txt");
File file2 = new File("b.txt");
//创建流
FileReader fr = null;
FileWriter fw = null;
//创建缓冲流
BufferedReader br = null;
BufferedWriter bw = null;
try {
fr = new FileReader(file1);
fw = new FileWriter(file2);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
//读数据
//方式1 使用char[]数组
// char[] cbuf = new char[10];
// int len;
// while ((len = br.read(cbuf)) != -1) {
// bw.write(cbuf, 0, len);
// }
//方式2 使用String
String data;
while ((data = br.readLine()) != null) {
bw.write(data + "n");
//bw.newline()同样实现换行
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
转换流
提供了字节流和字符流之间的转换,这两个流属于字符流
InputStreamReader:将InputStream(字节输入流)转换为Reader(字符输入流)
OutputStreamWriter:将Wrier(字符输出流)转换为OutputStream(字节输出流)
作用:字节流中数据都是字符时,转换为字符流操作更高效
很多时候我们使用转换流来处理文件乱码问题,实现编码和解码
编码:字符数组,字符串 ---> 字节,字节数组
解码:字节,字节数组 ---> 字符数组,字符串
字符集:
ASCII:美国标准信息交换码
用一个字节的7位可以表示
ISO8859-1:拉丁码表,欧洲码表
用一个字节的8为表示
GB2312:中国的中文编码表
最多两个字节编码所有字符
GBK:中国的中文编码表的升级
融合了更多的中文文字符号,最多两个字节编码
Unicode:国际标准码
融合了目前人类使用的所有字符,为每个字符分配唯一的字符码,所有的文字都用两个字节表示。存在问题:1、英文字母只用一个字节表示就足够了。2、如何区分ASCII和Unicode,计算机怎么知道两个字节表示一个字符而不是两个。3、如果和GBK等双字节编码方式相同(用最高位1/0表示一个字节和两个字节)就少了很多值无法用于表示字符,不够表示所有字符。
UTF-8:变长的编码方式 中文是三个字节
可以用1-4个字节来表示一个字符。每次8个位来传输数据,而UTF-16就是每次16个位。
Unicode > UTF-8
Unicode字符集只是定义了字符的集合和唯一编号,Unicode编码则是对UTF-8,UTF-16/UCS-2等具体编码方案的统称而已并不是具体的编码方案。
转换流的使用public class TestIO {
//字节输入流到字符输入流的转换
@Test
public void test() {
FileInputStream fis = null;
InputStreamReader isr = null;
try {
fis = new FileInputStream("a.txt");
//参数二指明了字符集,采用那个字符集取决于文件的字符集
isr = new InputStreamReader(fis, "UTF-8");
char[] cbuf = new char[2];
int len;
while ((len = isr.read(cbuf)) != -1) {
for (int i = 0; i < len; i++) {
System.out.print(cbuf[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//综合使用InputStreamReader,OutputStreamWriter
@Test
public void test1() {
FileInputStream fis = null;
FileOutputStream fos = null;
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
fis = new FileInputStream("a.txt");
fos = new FileOutputStream("a_GBK.txt");
isr = new InputStreamReader(fis, "UTF-8");
osw = new OutputStreamWriter(fos, "GBK");
char[] cbuf = new char[2];
int len;
while ((len = isr.read(cbuf)) != -1) {
osw.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
需要了解的流
标准输入输出流
public class TestIO {
public static void main(String[] args) {
test();
}
//从键盘输入字符串,要求将读到的整行字符串转大写输出,然后继续输入
//直到输入e或exit(不分大小写)时程序退出
public static void test() {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
String data = null;
System.out.println("请输入字符串:");
while (true) {
data = br.readLine();
if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data
)) {
System.out.println("程序结束");
break;
} else
System.out.println(data.toUpperCase(Locale.ROOT));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
打印流
将基本数据类型的数据格式转化为字符串输出
PrintStream和PrintWriter 是标准输入输出流的父类
public class TestIO {
//将编码为0-255的字符写入指定文件
@Test
public void test() {
PrintStream ps = null;
try {
File file = new File("a.txt");
//创建打印输出流
ps = new PrintStream(file);
if (ps != null) {
//把标准输出流(控制台输出)改成文件
System.setOut(ps);
}
for (int i = 0; i <= 255; i++) {
System.out.print((char) i);
if (i % 20 == 0) {
System.out.println();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (ps != null)
ps.close();
}
}
}
数据流
public class TestIO {
@Test
public void test() {
//将基本数据类型和字符串类型写入文件
//直接在文件中看可能乱码,要用DataInputStream的方式
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("a.txt"));
dos.writeUTF("GYQ");
dos.flush();
dos.writeInt(12);
dos.flush();
dos.writeBoolean(true);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//将文件中存储的基本数据类型和字符串类型读入到内存
//读取顺序要和写入的顺序一致 鸡肋
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("a.txt"));
String name = dis.readUTF();
int age = dis.readInt();
boolean isMale = dis.readBoolean();
System.out.println("name:" + name + " age:" + age + " isMale:" + isMale);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
对象流
序列化,反序列化
自定义类实现序列化的要求:
实现接口Serializable
提供一个全局常量:serialVertionUID
除了当前类实现Serializable接口外,其内部所有属性也必须是可序列化的(默认情况下基本数据类型也是可序列化的)
public class TestIO {
@Test
public void test() {
//序列化过程
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("a.xxx"));
oos.writeObject(new String("我爱吃肉!"));
oos.writeObject(new Person("GYQ", 18, 99.9));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化的过程
ObjectInputStream ois = null;
Object object = null;
String str = "";
Person p = null;
try {
ois = new ObjectInputStream(new FileInputStream("a.xxx"));
object = ois.readObject();
str = (String) object;
object = ois.readObject();
p = (Person) object;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(str);
System.out.println(p);
}
}
//自定义类
class Person implements Serializable {
//版本控件(唯一标识)
public static final long serialVersionUID = 4864864465L;
private String name;
private int age;
private double score;
public Person(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + ''' +
", age=" + age +
", score=" + score +
'}';
}
}
随机存储文件流
public class TestIO {
//实现图片复制
@Test
public void test() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile("1.jpg", "r");
raf2 = new RandomAccessFile("2.jpg", "rw");
byte[] bytes = new byte[1024];
int len;
while ((len = raf1.read(bytes)) != -1) {
raf2.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (raf1 != null)
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (raf2 != null)
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("复制完成!");
}
//对文本文件的操作
@Test
public void test2() {
RandomAccessFile raf = null;
try {
//作为输出流,如果文件不存在则创建,文件存在覆盖文件内容(默认情况下从文件开头开始)
raf = new RandomAccessFile("a.txt", "rw");
raf.write("天涯何处逢知己".getBytes(StandardCharsets.UTF_8));
//将指针调到角标为3的位置
raf.seek(9);
raf.write("角标移动到9的位置".getBytes(StandardCharsets.UTF_8));
//实现插入 保存指针后的内容,在在指针位置写入数据,再追加保存的内容
//实现追加
raf.seek(raf.length());
raf.write("asdsa".getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
NIO
先了解
NIO2中Path,Paths和Files核心APIPath
Paths
Files
网络编程
概述
如何实现网络中的主机相互通信
通信双方地址
IP
端口号
一定的规则(即网络通信协议,有两套参考模型)
OSI参考模型:模型过于理想化,未能在因特网上进行广泛推广
TCP/IP参考模型(或TCP/IP协议):事实上的国际标准
TCP和UDP
InetAddress类在Java中使用InetAddress类代表IP
@Test
public void test() {
InetAddress inetAddress1 = null;
InetAddress localHost = null;
InetAddress inetAddress2 = null;
String address = "";
String hostName = "";
try {
//获取指定IP地址的InetAddress对象
inetAddress1 = InetAddress.getByName("192.168.0.0");
//获取指定域名的IP地址的InetAddress对象
inetAddress2 = InetAddress.getByName("www.baidu.com");
//获取本机IP地址的InetAddress对象
localHost = InetAddress.getLocalHost();
//获取主机域名
hostName = inetAddress2.getHostName();
//获取主机地址
address = inetAddress2.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
System.out.println(inetAddress1);
System.out.println(inetAddress2);
System.out.println(localHost);
System.out.println(hostName);
System.out.println(address);
}
TCP网络编程
例1:实现TCP通信
public class TCPTest {
//客户端
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
//创建Socket对象,指明服务器端的ip和端口号
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
socket = new Socket(inetAddress, 8888);
//获取输入流,用于输出数据
os = socket.getOutputStream();
//写入数据的操作
os.write("你好,我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//资源的关闭
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//服务器端
@Test
public void server() {
ServerSocket serverSocket = null;
InputStream is = null;
Socket socket = null;
ByteArrayOutputStream baos = null;
try {
//创建服务器端的ServerSocket,指明自己的端口号
serverSocket = new ServerSocket(8888);
//调用accept()表示接收来自客户端的Socket
socket = serverSocket.accept();
//获取输入流
is = socket.getInputStream();
//不建议使用 输出可能中文乱码
// byte[] buffer = new byte[20];
// int len;
// while ((len = is.read(buffer)) != -1) {
// String str = new String(buffer, 0, len);
// System.out.print(str);
// }
//读取输入流中的数据
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[10];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
System.out.println("来自于:" + socket.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
例2:客户端发送文件给服务端(与上方代码相似,只是多使用了文件流)
客户端
服务端
例三:服务端接收完数据给客户端反馈,客户端接收反馈
服务端接收完数据
客户端
注意此时要先关闭上面的输出流,否则会阻塞
UDP网络编程public class UDPTest {
//发送端
@Test
public void sender() throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = "我是UDP方式发送的";
byte[] data = str.getBytes();
InetAddress inetAddress = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data, 0, data.length, inetAddress, 8888);
socket.send(packet);
socket.close();
}
//接收端
@Test
public void receiver() throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
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()));
}
}
URL编程
URL类的使用
public class UDPTest {
//URL类的方法
@Test
public void test1() {
try {
//URL对象
URL url = new URL("http://localhost:8080/myweb/index.html?Id=1");
//获取该URL的协议名
System.out.println(url.getProtocol());
//获取该URL的主机名
System.out.println(url.getHost());
//获取该URL的端口号
System.out.println(url.getPort());
//获取该URL的文件路径
System.out.println(url.getPath());
//获取该URL的文件名
System.out.println(url.getFile());
//获取该URL的查询名
System.out.println(url.getQuery());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
//从指定URL获取资源
@Test
public void test2() {
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL("http://localhost:8080/myweb/1.mp4");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("copy.mp4");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("下载成功!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


