目录标题
一、File类
1、file类对象可以表示一个文件或一个目录
2、file类不负责读写文件,常常作为参数传入io流中创建对象,读写文件
1、构造器
注意:当new FIle()对象的时候,如果指定的文件或者目录不存在,那么这个对象只是一般的对象。只有文件和路径存在,才能进行一些文件操作。
//构造器一
//相对路径
File file = new File("test.txt");
//绝对路径
File file1 = new File("C:\\Users\\15594\\Desktop\\test.txt");
//获取目录对象
File file2 = new File("C:\\Users\\15594\\Desktop", "目录");
//获取文件对象
File file3 = new File(file2, "hi.text");
2、常用的方法
File file = new File("test.txt");
System.out.println("获取绝对路径:"+file.getAbsolutePath());
System.out.println("返回传入的路径、文件名"+file.getPath());
System.out.println("判断是不是文件:"+file.isFile());
System.out.println("是不是目录:"+file.isDirectory());
System.out.println("判断文件是否存在"+file.exists());
System.out.println("返回文件长度(以字节为单位:)"+file.length());
//判断此文件是否存在,不存在则新建一个文件
File file6 = new File("hi.txt");
try {
file6.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//创建指定的一个文件夹
file6.mkdir();
//创建指定的文件路径
file6.mkdirs();
//删除一个文件或者目录(当目录下的所有文件夹为空时)
file6.delete()
//更改文件名,注意:new File("hello.txt")这个文件是不存在的,才能修改成功。
file6.renameTo(new File("hello.txt"));
3、获取文件夹的内容
File file4 = new File("C:\\Users\\15594\\IdeaProjects\\javaSE_study\\src");
String[] list = file4.list();
for (String s : list) {
System.out.println(s);
}
File[] files = file4.listFiles();
for (File file5 : files) {
System.out.println(file5);
}
二、IO流
1、IO六分类
注意:InputStream、OutputStream、Reader、Writer是抽象类
2、按照数据单位——字节流(InputStream、OutputStream)和字符流(Reader、Writer)
2.1、字符流的实现类——FIleReader、FileWriter
注意:字符流不能处理图片,视频等格式的文件,一般用于处理文本
- 一个个字符读取
package file.IO;
import java.io.*;
/**
*
* 字符型的字节流
* @author 15594
*/
public class FileReaderAndWriter {
public static void main(String[] args) {
File file = new File("hello.txt");
System.out.println(file.exists());
System.out.println(file.length());
if (file.isFile()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
read(file);
}
private static void read(File file) {
FileReader fileReader =null;
try {
fileReader = new FileReader(file);
int read = fileReader.read();
System.out.println("此文件的编码格式:"+fileReader.getEncoding());
if (read!=-1){
while (read!=-1){
read = fileReader.read();
System.out.print((char) read);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader!=null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 按指定的数组大小进行读取
package file.IO;
import java.io.*;
/**
*
* 字符型的字节流
* @author 15594
*/
public class FileReaderAndWriter {
public static void main(String[] args) {
File file = new File("hello.txt");
System.out.println("文件内容字符长度:"+file.length());
if (file.isFile()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// read(file);
try {
reads(file);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void reads(File file) throws IOException {
FileReader fileReader = new FileReader(file);
char[] chars = new char[3];
int len = 0;
while ((len = fileReader.read(chars)) !=-1){
for (int i = 0; i <len ; i++) {
System.out.print(chars[i]);
}
System.out.println();
}
fileReader.close();
}
private static void read(File file) {
FileReader fileReader =null;
try {
fileReader = new FileReader(file);
int read = fileReader.read();
System.out.println("此文件的编码格式:"+fileReader.getEncoding());
if (read!=-1){
while (read!=-1){
read = fileReader.read();
System.out.print((char) read);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader!=null){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- write写入文件
private static void write(File file) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
//覆盖写
fileWriter.write("你好?");
//追加写
fileWriter.append("123");
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileWriter!=null){
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.2、字节流的实现类——FileInputStream、FileOutputStream
注意;字节流处理文本文件可能会出现乱码。字节流可以对文本文件就行复制
package file.IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author 15594
*/
public class InOutPutStream {
public static void main(String[] args) {
File file = new File("C:\\Users\\15594\\Desktop\\测试\\welcome.jpg");
File file2 = new File("C:\\Users\\15594\\Desktop\\测试\\sea.png");
File file1 = new File("welcome.jpg");
System.out.println(file.getAbsolutePath());
System.out.println(file1.length());
try {
if (!file1.exists()){
file1.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
output(file,file1);
}
private static void output(File file, File file1) {
FileInputStream input = null;
FileOutputStream out = null;
try {
input = new FileInputStream(file);
out = new FileOutputStream(file1,false);
byte[] bytes = new byte[46];
int len = 0;
while ((len = input.read(bytes))!=-1){
out.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void input(File file) {
}
}
可以读取文本文件,但有中文时(不是一个字节的字符)会出现乱码
File file = new File("test1.txt");
file.createNewFile();
System.out.println(file.getAbsolutePath());
System.out.println(file.getPath());
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] b = new byte[5];
int len = 0;
while ((len = fileInputStream.read(b))!=-1){
System.out.print(new String(b,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileInputStream!=null){
fileInputStream.close();
}
}
3、缓冲流
- 缓冲流能加快读取和写入文件的速度
- 缓冲流是处理流,创建对象时需要传入节点流(文件流)。
- 使用处理流,在关闭流时,只需要关闭最外层的流,内层的流会自动关闭
- 缓冲流既有字节流,也有字符流
3.1BufferedOutputStream、BufferedOutputStream
package file.IO;
import java.io.*;
/**
* 缓冲流
* @author 15594
*/
public class BufferedInOutputStream {
public static void main(String[] args) {
//注意:读取的文件必须确定是存在的
File file = new File("C:\\Users\\15594\\Desktop\\01-视频.avi");
//注意:写入的文件可以不存在,在写入时若文件不存在就会创建文件
File file1 = new File("C:\\Users\\15594\\Desktop\\02-视频-copy.avi");
copy(file,file1);
}
private static void copy(File file, File file1) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(file1);
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes))!=-1){
bos.write(bytes,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
-
缓冲流写入数据的过程:
将文件中指定大小的一段数据读取出来,然后方法缓冲流自带的缓冲区中,缓冲区满后将数据存入文件 -
flush()的作用——刷新缓冲区
当调用flush()时,即使缓冲区没有满也会立即将缓冲区的内容刷入文件中。
3.2BufferedWriter、BufferedReader
- BufferedReader里面有一个读取一行的方法——readLine()
- BufferedWriter里面有一个换行的方法——newLine()
package file.IO;
import java.io.*;
/**
* @author 15594
*/
public class BufferedWriterReader {
public static void main(String[] args) {
File file = new File("test.txt");
File file1 = new File("test-copy.txt");
copy(file,file1);
}
private static void copy(File file, File file1) {
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file1);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
int len = 0;
char[] chars = new char[10];
while ((len = bufferedReader.read(chars))!=-1){
bufferedWriter.write(chars,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedWriter!=null){
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4、转换流
4.1、InputStreamReader——将字节流转换成字符流(可以理解为解码,将看不懂的字节转换成字符,然后输入内存)
首先从文件中以字节读取文件,然后通过转换流将字节转换成字符,最后将转换后的字符输入内存
4.2、OutputStreamWriter——将字符流转换成字节流(可以理解为编码,将看得懂的字符转换成看不懂的字节,然后存入文件)
首先从内存中将字符转换成字节,然后写入文件中
4.3、deom——更改文件的编码格式
package file.IO;
import java.io.*;
public class InputStreamReader_ {
public static void main(String[] args) {
File file = new File("test.txt");
File file1 = new File("test-转换流-gbk.txt");
File file2 = new File("test-转换流-utf.txt");
System.out.println();
// UTFConversionGBK(file,file1);
GBKConversionUTF(file1,file2);
}
private static void GBKConversionUTF(File file1, File file2) {
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
FileInputStream fileInputStream = new FileInputStream(file1);
FileOutputStream outputStream = new FileOutputStream(file2);
isr = new InputStreamReader(fileInputStream,"GBK");
osw = new OutputStreamWriter(outputStream,"UTF-8");
int len = 0;
char[] chars = new char[10];
while ((len = isr.read(chars))!=-1){
osw.write(chars,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} 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();
}
}
}
}
private static void UTFConversionGBK(File file, File file1) {
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(file1);
isr = new InputStreamReader(fileInputStream,"UTF-8");
osw = new OutputStreamWriter(outputStream,"GBK");
int len = 0;
char[] chars = new char[10];
while ((len = isr.read(chars))!=-1){
osw.write(chars,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} 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();
}
}
}
}
}
5、随机流
注意:同一个流操作文件时,注意文件读取、写入的指针位置
package IO;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
*
* 随机存取流——能同时充当输入、输出流、输入输出流
* @author 15594
*/
public class RandomStream {
public static void main(String[] args) throws IOException {
/**mode参数可取,r、rw、rwd、rws r为读取流、rw为可读可写流*/
RandomAccessFile randomAccessFile = new RandomAccessFile("random.txt","rw");
randomAccessFile.writeUTF("你好,RandomStream");
randomAccessFile.seek(0);
String s = randomAccessFile.readUTF();
System.out.println(s);
randomAccessFile.close();
}
}
三、对象流与序列化
1、对象流
将内存中的对象持久化保存到磁盘(文件)中,或者读取文件中的对象到内存
注意:
1、这里的对象必须是可序列化的,也就是实现了Serializable 接口
2、Serializable 接口是一个空接口,不需要实现方法,只是一个标识接口
3、读取顺序必去与写入顺序一致
package IO.objectstream;
import java.io.*;
/**
* @author 15594
*/
public class ObjectStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
/**
*1、序列化过程:将内存中的java对象保存到磁盘中或者进行网络传输
* */
//将对象存入文件
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new String("你好?"));
oos.writeObject(new Person(1,"lihua",18,new Account(1,8888.1),666));
oos.flush();
oos.close();
//读取文件中的对象,注意读取顺序必去与写入顺序一致
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
String s = (String) ois.readObject();
Person person = (Person) ois.readObject();
System.out.println(s);
System.out.println(person);
ois.close();
}
}
2、序列化
序列化过程:将内存中的java对象转换成二进制保存到磁盘中或者进行网络传输
序列化步骤:
1、需要序列化的类实现Serializable 接口
2、提供一个序列化版本号,private static final long serialVersionUID = 612794470754667710L; 值是自定义的,不要重复
package IO.objectstream;
import java.io.Serializable;
/**
* @author 15594
*/
public class Person implements Serializable {
private static final long serialVersionUID = 612794470754667710L;
private int id;
private String name;
private int age;
public Person() {
}
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
注意:
1、在序列化时必须提供序列化版本号,因为在读取对象时,是按照序列化版本号区分对象的(类似身份证)。如果不指定版本号,Java虚拟机会自动生成一个,但是在类发生变化时会再次生成一个新的版本号,因此如果类发生了变化,之前序列化的对象就会无法识别。
2、序列化时必须保证里面的所有属性是可序列化的。
3、当成员属性被static、transient修饰时,不会将这些成员序列化(也就是不会将这些值保存到文件中,当反序列时会使用默认值比如0,null)
package IO.objectstream;
import java.io.Serializable;
/**
* @author 15594
*/
public class Person implements Serializable {
private static final long serialVersionUID = 612794470754667710L;
private int id;
private String name;
private int age;
private Account account;
// transient、static不会序列化,(static是属于类的,不是对象因此不会序列化)
private transient int a ;
private static int b=888 ;
public Person() {
}
public Person(int id, String name, int age, Account account, int a) {
this.id = id;
this.name = name;
this.age = age;
this.account = account;
this.a = a;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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 Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public static int getB() {
return b;
}
public static void setB(int b) {
Person.b = b;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", account=" + account +
", a=" + a +
'}';
}
}
package IO.objectstream;
import java.io.Serializable;
/**
* @author 15594
*/
public class Account implements Serializable {
private int id;
private Double money;
private static final Long serialVersionUID = 89310913221L;
public Account() {
}
public Account(int id, Double money) {
this.id = id;
this.money = money;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", money=" + money +
'}';
}
}
四、网络编程
package IO.socket;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author 15594
*/
public class SocketTest {
public static void main(String[] args) {
server();
}
private static void server() {
ServerSocket serverSocket = null;
Socket accept = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
serverSocket = new ServerSocket(8899);
accept = serverSocket.accept();
inputStream = accept.getInputStream();
// 这样写会可能出现中文乱码
// byte [] bytes = new byte[10];
// int len = 0;
// while ((len = inputStream.read(bytes))!=-1){
// String s = new String(bytes, 0, len);
// System.out.println(s);
// }
byteArrayOutputStream = new ByteArrayOutputStream();
byte [] bytes = new byte[10];
int len = 0;
while ((len = inputStream.read(bytes))!=-1){
byteArrayOutputStream.write(bytes,0,len);
}
String string = byteArrayOutputStream.toString();
System.out.println(string);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (byteArrayOutputStream!=null){
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept!=null){
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class Client{
public static void main(String[] args) {
client();
}
private static void client() {
Socket socket = null;
OutputStream outputStream = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 8899);
outputStream = socket.getOutputStream();
outputStream.write("你好,我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
deom模拟客户端下载图片
package IO.socket;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 通过网络传输一张图片
*
* 客户端获取服务端的一张图片
* @author 15594
*/
public class SocketTest1 {
public static void main(String[] args) {
server();
}
private static void server() {
ServerSocket serverSocket = null;
Socket accept = null;
BufferedInputStream bis =null;
OutputStream outputStream =null;
try {
bis = new BufferedInputStream(new FileInputStream("welcome.jpg"));
serverSocket = new ServerSocket(8899);
accept = serverSocket.accept();
System.out.println("创建连接的用户ip:"+accept.getInetAddress());
outputStream = accept.getOutputStream();
byte [] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (accept!=null){
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
server();
}
}
}
class Client1{
public static void main(String[] args) {
client();
}
private static void client() {
Socket socket = null;
InputStream inputStream = null;
BufferedOutputStream bos = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 8899);
inputStream = socket.getInputStream();
bos = new BufferedOutputStream(new FileOutputStream("来自服务器的图片.jpg"));
byte [] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes))!=-1){
bos.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}