File类:定义一个文件或目录对象
Files类:工具类
public class Main1 {
public static void main(String[] args) {
List<String> nameList = Arrays.asList("aaa","bbb","ccc","ddd");
try {
//Files工具类:将指定文本(集合)写入指定文件中
Files.write(Paths.get("F:\\SQLyog\\shiyuan"), nameList);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Main2 {
public static void main(String[] args) {
try {
//Files工具类:读取指定文件中的所有文本
List<String> lineList = Files.readAllLines(Paths.get("F:\\SQLyog\\shiyuan"));
for(String name : lineList) {
System.out.println(name);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
IO流:①字节流②字符流
·字节流
·输入流(InputStream):从磁盘的文件中,读取数据至内存
常见操作:
read():每次读取一个字节
read(byte[] buff):每次读取n个字节
readObject():每次读取一个对象
常见子类:
FileInputStream:文件输入流
BufferedInputStream:自带缓冲区的输入流
ObjectInputStream:对象输入流
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
public class Main3 {
public static void main(String[] args) {
//创建一个基于读取文件方式的输入流
try(FileInputStream in = new FileInputStream("F:\\Apesource-java\\fsqlp\\lanqiu.jpg");){
//方式一:每次读取一个字节数据,读取至末尾时,返回-1
int data1 = in.read();
int data2 = in.read();
int data3 = in.read();
System.out.println(data1);
System.out.println(data2);
System.out.println(data3);
//通过循环,读取所有字节数据
int data = -1;
while( (data = in.read()) != -1) {
System.out.println(data);
}
//写法二: 每次读取若干个字节数据,并保存至一个字节数组中
// read()方法返回本次读取到的字节长度
byte[] buff = new byte[256000];
int len = in.read(buff);
System.out.println("本次读取到的内容:" + Arrays.toString(buff));
System.out.println("本次读取到的长度:" + len);
byte[] buff = new byte[128];
int len = 0;
while((len = in .read(buff)) > 0) {
System.out.printf("本次读取到%d个字节:%s\n", len, Arrays.toString(buff));
}
}catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
·输出流 (OutputStream):将程序中的数据,写入磁盘的文件中
常见操作:
write(byte[] buff):将字节数组buff中所有的内容一次性写入
write(byte[] buff, int offset,int length):将字节数组buff中指定的内容写入
writeObject():写入一个对象
常见子类:
FileOutputStream:文件输出流
BufferedOutputStream:自带缓冲区的输出流
ObjectOutputStream:对象输出流
public class Main4 {
public static void main(String[] args) {
try {
//读取到一张图片的字节数据
byte[] imgData = Files.readAllBytes(Paths.get("F:\\Apesource-java\\fsqlp\\lanqiu.jpg"));
//创建文件输出流
try(FileOutputStream out = new FileOutputStream("F:\\Apesource-java\\fsqlp\\fanfan.jpg");){
out.write(imgData);
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
//边读边写
public class Main5 {
public static void main(String[] args) {
try (FileInputStream in = new FileInputStream("F:\\Apesource-java\\fsqlp\\lanqiu.jpg");
FileOutputStream out = new FileOutputStream("F:\\Apesource-java\\fsqlp\\shiqi.jpg")){
byte[] buff = new byte[128];
int len = 0;
while((len = in.read(buff)) > 0) {
out.write(buff, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
·字符流
·输入流(Reader)
常见子类:
FileReader:读取文本文件的字符流
BufferedReader:缓冲区字符输入流
InputStreamReader:转换流
·输出流(Writer)
常见子类:
FileWriter
BufferedWriter
OutputStreamWriter
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.time.LocalTime;
import java.util.Timer;
import java.util.TimerTask;
public class Zero13 {
public static void main(String[] args) {
System.out.printf("%s心跳检查程序启动……\n",LocalTime.now());
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("ping www.163.com");
try(BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
BufferedWriter bw = new BufferedWriter(
new FileWriter("F:\\Apesource-java\\fsqlp\\mrn.txt",true));){
String line = null;
while((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
}
}catch (Exception e) {
}
}
}, 1000, 2000);
}
}
·序列化和反序列化:将“对象”以字节流的方式,进行写入或读取
序列化:将指定对象,以”字节流“的方式写入一个文件或网络中
反序列化:从一个文件或网络中,以”字节流“的方式读取到对象
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Demo02 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("范世錡");
list.add("朱嘉琦");
list.add("易烊千玺");
//序列化:将“对象”写入至文件
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\img_back\\list.miao"));){
//将list集合对象,写入list.miao文件中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Demo03 {
public static void main(String[] args) {
//反序列化:文件中读取一个对象
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\img_back\\list.miao"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用要求:
需要进行序列化操作的对象,必须实现Serializable接口,使用transient关键字修饰的成员变量,在序列化时,不会被写入;在反序列化时,不会被读取。
使用场景:
本地缓存,在网络环境下,将对象以流的方式,进行传输
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Demo04 {
public static void main(String[] args) {
Order order = new Order("SN001",567.89,"AX59",0.5);
//序列化时,该对象的类型,必须实现Serializable接口
try(ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("D:\\\\img_back\\order.ser")))){
//写入对象
oos.writeObject(order);
}catch (IOException e) {
e.printStackTrace();
}
}
}
class Order implements Serializable{
/**
* 序列化版本号
*/
private static final long serialVersionUID = -4420026594104876273L;
private String orderNo;//订单编号
private double pay;//支付金额
private double sale;//折扣
//transient关键字修饰的成员变量,在序列化时,不会被写入
private transient String validateCode;//验证码
//无参构造方法
public Order() {
this.orderNo="SN00x";
this.pay=0.1;
}
//有参构造方法
public Order(String orderNo, double pay,String validateCode,double sale) {
this.orderNo = orderNo;
this.pay = pay;
}
public double getSale() {
return sale;
}
public void setSale(double sale) {
this.sale = sale;
}
public String getValidateCode() {
return validateCode;
}
public void setValidateCode(String validateCode) {
this.validateCode = validateCode;
}
@Override
public String toString() {
return "Order [orderNo=" + orderNo + ", pay=" + pay + ", sale=" + sale + ", validateCode=" + validateCode + "]";
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public double getPay() {
return pay;
}
public void setPay(double pay) {
this.pay = pay;
}
}
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Demo05 {
public static void main(String[] args) {
//反序列化:从文件中读取一个对象
try(ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("D:\\img_back\\order.ser")))){
Order order = (Order)in.readObject();
System.out.println(order);
}catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
}
·Properties
*.properties格式的文件,内容是Key-Value键值对格式(key=value),注释使用#,使用Properties类完成*properties格式文件的读取和写入,读取使用 load(),写入使用store(),Properties类本质其实是一个Map集合,是Hashtable类的子类。
//创建Properties类型的对象props,用于读取*.properties类型的文件
public class Demo08 {
public static void main(String[] args) {
try(FileInputStream fis = new FileInputStream("D:\\img_back\\config.properties")){
Properties props = new Properties();
props.load(fis);
System.out.println(props.get("029"));
System.out.println(props);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Demo09 {
public static void main(String[] args) {
//读取classpath路径下的*.properties文件
try(InputStream in = Demo09.class.getResourceAsStream("config.properties")){
Properties props = new Properties();
props.load(in);
System.out.println(props);
}catch(IOException e) {
e.printStackTrace();
}
}
}
//properties文件的写入操作
public class Demo10 {
public static void main(String[] args) {
Properties props = new Properties();
props.put("version", "v0.000001");
props.put("active-code", "bgioadcnpkxkMXajSOIHDOIPOSvsjbvsojcask");
try(FileOutputStream fos = new FileOutputStream("D:\\img_back\\app.properties")){
//将键值对,通过输出流写入指定文件,并添加注释
props.store(fos, "My application basic properties data.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}