文章目录
- Java IO
- File 类
- 文件编码
- IO 流
- 四大IO抽象类对象的常用方法:
- 一、IO 文件流
- 1. 字节流处理文件
- 2. 字符流处理文件
- 二、字节数组流
- IO 工具类
- 装饰器设计模式
- 字节缓冲流
- 字符缓冲流
- 字符转换流
- 数据流
- 对象流
- 打印流
- 文件序列流
- 文件分割
- 文件合并
- CommonIO 类
Java IO
利用 Java IO 你可以访问文件与目录,以及如何以文本格式和二进制格式来读写数据。
Java IO 中的八大对象:
- File (文件类)
- InputStream(字节输入流)
- OutputStream(字节输出流)
- Read(字符输入流)
- Write(字符输出流)
- Closeable
- Flushable
- Serializable
File 类
File 类常用的函数
方法 | 说明 |
pathSeparator | separator | 路径 | 路径分隔符 |
getName() | getPath() | getAbsolutePath() | getParent() | 获取文件名或路径名 |
exists() | isFile() | isDirectory() | 判断文件状态 |
length() | 文件长度 |
createNewFile() | delete() | 创建新文件 | 删除文件 |
mdkdir() | mkdirs() | 创建目录,mkdir需要根目录存在 |
list() | 下级名称 |
listFiles() | 下级File |
listRoots() | 根路径 |
【示例】:创建文件与文件夹
File src = new File("IO.png");
//获取文件基本信息
System.out.println("名称:" + src.getName());
System.out.println("路径:" + src.getPath());
System.out.println("绝对路径:" + src.getAbsolutePath());
System.out.println("父路径:" + src.getParent());
System.out.println("父路径:" + src.getParentFile().getName());
//文件状态
System.out.println("是否存在:" + src.exists());
System.out.println("是否是文件:" + src.isFile());
System.out.println("是否是文件夹:" + src.isDirectory());
//文件的创建与删除
boolean flag;
src = new File("a/b/c/d.txt");
flag = src.createNewFile();
System.out.println(flag);
src.delete();
//文件夹的创建与删除
File dir = new File();
boolean flag1 = dir.mkdirs();
System.out,println(flag1);
//列出文件夹的下一级
File dir1 = new File();
String[] fileNames = dir1.list();
for(String s:fileNames){
System.our.println(s);
}
//获取文件集合下的文件夹
File[] subFiles = fir1.listFiles();
for(File s:subFiles){
System.out.println
}
文件编码
在中文编程中常用的文件编码:
- ASCII
- UTF-8
- ISO-8859-1
- UTF-16
- UTF-16 LE
- UTF-16 BE
编码与解码的区别
编码:字符串 --> 字节
解码:字节 --> 字符串
【示例】
String msg = "这是一个不能说的秘密":
byte[] datas = msg.getBytes();
System.out.println(datas.length);//默认使用工程的字符集
datas = msg.getBytes("utf-16");
System.out.println(datas.length);
//解码
msg = new String(datas,0,datas.length,"utf-8");
System.out.println(msg);
PS: 解码过程中出现乱码的原因
- 字节数不够
- 字符集不统一
IO 流
**输入流:**数据从数据源流向程序的过程为输入流
**输出流:**数据从程序流出时的过程称为输出流
IO 流有四大类,依据处理的数据类型的角度来分类可以分为:字节流(InputStream,OutputSteam),字符流(Reader,Writer)
依据功能来分类可以分为节点流和处理流。
四大IO抽象类对象的常用方法:
InputStream 类:
方法 | 描述 |
void close() | 关闭输入流并释放系统资源 |
abstract int read() | 从输入流读取下一个字节 |
int read(byte[] b) | 从输入流中读取一些字节数,并将它们存储到缓冲阵列 b 中 |
int read(byte[] b,int off, int len) | 从输入流中读取最多 len 个字节到字节数组 |
byte[] readAllBytes() | 从输入流中读取所有剩余字节 |
OutputStream类:
方法 | 描述 |
void close() | 关闭输出流并释放所有与此流相关的资源 |
void flush() | 刷新输出流并强制任何缓冲的输出字节被写出 |
void write(byte[] b) | 将字节数组 b 中的字节写入到输出流 |
void write(byte[] b, int off, int len) | 从指定字节数组写入 len 个字节,从偏移量 off 开始输出到输出流 |
abstract void write(int b) | 将指定的字节写入次输出流。 |
Reader 类: 用于读取字符流抽象类
方法 | 描述 |
int read() | 读一个字符 |
int read(char[] cbuf) | 将字符读入数组 |
abstract int read(char[] cbuf, int off, int len) | 读入一部分字符数组 |
Writer 类: 用于写入字符流的抽象类
方法 | 描述 |
abstract void close() | 关闭流,先刷新 |
abstract void flush() | 刷新流 |
void write(char[] cbuf) | 写入一个字符数组 |
abstract void write(char[] cbuf, int off, int len) | 写入字符数组的一部分 |
void write(int c) | 写入一个字符 |
void write(String str) | 写一个字符串 |
void write(String str, int off, int len) | 写一个字符串的一部分 |
Writer append(char c) | 将指定字符附加到此作者 |
Writer append(CharSequence csq) | 将指定字符序列附加到此作则 |
Writer append(CharSequence csq, int start, int end) | 将指定字符序列的子序列附加到此作者 |
一、IO 文件流
文件流需要用到 FileInputStream & FileOutputStream
1. 字节流处理文件
【示例】
File src = new File("abc.txt");
try{
InputStream is = new FileInputStream();
int data1 = is.read();
int data2 = is.read();
int data3 = is.read();
System.out.println(data1);
System.out.println(data2);
System.out.println(data3);
}catch(FileNotFoundException 1e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
is.close();
}
【示例】
File src = new File("abc.txt");
try{
InputStream is = new FileInputStream();
int temp;
while((temp = is.read())!=-1){
System.out.println(temp);
}
}catch(FileNotFoundException 1e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(is != null){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
File src = new File("abc.txt");
InputStream is = null;
try{
is = new FileInputStream();
byte[] car = new byte[3];
int len = -1;
while((len = is.read(car))!=-1){
String str = new String(car,0,len);
System.out.println(str);
}
}catch(FileNotFoundException 1e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(is != null){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】 test04
File src = new File("abc.txt");
OutputStream os = null;
try{
os = new FileOutputStream(src);
String msg = "IO is so easy";
byte[] datas = msg.getBytes();
os.write(datas,0,datas.length);
os.flush();
}catch(FileNotFoundException 1e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(os != null){
os.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
**【示例】:**文件拷贝
public static void copyFile(String srcPath,String destPath){
File src = new File(srcPath);
File dest = new File(destPath);
OutputStream os = null;
InputStream is = null;
try{
is = new FileInputStream(src);
os = new FileOutputStream(dest);
byte[] flush = new byte[1024];
int len =-1;
while((len = is.read(flush))!=-1){
os.write(flush,0,len);
}
}catch(IOException e){
e.printStackTrace();
}catch(FileNotFoundException e){
e.printStackTrace();
}finally{
try{
if(os!=null){
os.close();
}
}catch(IOException e){
e.printStackTrace();
}
try{
if(is != null){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
2. 字符流处理文件
【示例】
File src = new File("a.txt");
Reader reader = null;
try{
reader = new FileReader(src);
char[] flush = new char[1024];
int len = -1;
while((len = reader.read(flush))!=-1){
String str = new String(flush,0,len);
System.out.println(str);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(reader != null){
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
File src = new File("dest.txt");
Writer writer = null;
try{
writer = new FileWriter(src);
String msg = "Java IO is to Easy";
char[] datas = msg.toCharArray();
writer.write(datas,0,datas.length);
writer.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer != null){
writer.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
File src = new File("dest.txt");
Writer writer = null;
try{
writer = new FileWriter(src);
String msg = "Java IO is to Easy";
writer.write(msg);
writer.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer != null){
writer.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
File src = new File("dest.txt");
Writer writer = null;
try{
writer = new FileWriter(src);
String msg = "Java IO is to Easy";
writer.append(msg).append("撒花完结");
writer.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer != null){
writer.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
二、字节数组流
字节数组流相较于文件流的区别:
- 文件流是存在于硬盘中的,因此需要 jvm 通过 OS 来进行读取,而字节数组流则可以直接访问
- 文件流对传输的数据大小没有太大的限制,字节数组流进行数据传输时要保证数据尽可能的小
- 文件流需要关闭,字节数组流不需要关闭
- 任何数据都可以转成字节数组流。
【示例】
byte[] datas = "talk is cheap show me the code".getBytes();
ByteArrayInputStream bais = null;
try{
bais = new ByteArrayInputStream(datas);
byte[] flush = new byte[5];
int len = -1;
while((len = bais.read(flush))!= -1){
String str = new String(flush,0,len);
System.out.println(str);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(bais != null){
bais.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
byte[] dest;
ByteArrayOutputStream baos = null;
try{
baos = new ByteArrayOutputStream(dest);
String msg = "talk is cheap show me the code";
byte[] datas = msg.getBytes();
baos.write(datas,0,datas.length);
baos.flush();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(baos != null){
baos.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
public static byte[] fileToByteArray(String filePath){
File src = new File(filePath);
byte[] dest = null;
InputStream is = null;
ByteArrayOutputStrem baos = null;
try{
is = new FileInputStream(src);
baos = new ByteArrayOutputStream(dest);
byte[] flush = new byte[1024];
int len = -1;
while((len = is.read(flush))!= -1){
baos.write(flush,0,len);
}
baos.flush();
return dest;
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(is != null){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
public static void byteArrayToFile(byte[] src,String filePath){
File dest = new File(filePath);
ByteArrayInputStream bais = null;
OutputStream os = null;
try{
bais = new ByteArrayInputStream(src);
os = new FileOutputStream(dest);
byte[] flush = new byte[1024];
int len = -1;
while((len = bais.read(flush)) != -1){
os.write(flush,0,len);
}
os.flush()
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(os != null){
os.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
IO 工具类
【示例】
public calss FileUtils{
public static void mian(String args[]){
try{
InputStream is = new FileInputStream(new File("a.txt"));
OutputStream os = new FileOutputStram(new File("b.txt"));
copy(is,os);
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public static void copy(InputStream is,OutputStream os){
...
}
public static void close(InputStream is,OutputStram os){
try{
if(is != null){
is.close();
}
if(os != null){
os.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void close(Closeable... ios){
for(io:ios){
try{
if(io != null){
io.close();
}
}catch(IOException e){
e.printStackTrace
}
}
}
public static void close(InputStream is,OutputStram os){
try(is;os){
if(is != null){
is.close();
}
if(os != null){
os.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
装饰器设计模式
装饰器设计模式有四大组件:
- 抽象组件: 需要装饰的抽象对象(接口或抽象父类)
- 具体组件: 需要装饰的对象
- 抽象装饰类: 包含对抽象组件的引用以及装饰者共有的方法
- 具体装饰类: 被装饰的对象
【示例】
//抽象组件
interface Drink{
double cost();
String info();
}
//具体组件
class Coffee implements Drink{
private String name = "原味咖啡";
@Override
public double cost(){
return 10;
}
@Override
public String info(){
return name;
}
}
//抽象装饰类
abstract class Decorate implements Drink{
private Drink drink;
public Decorate(Drink drink){
this.drink = drink;
}
@Override
public double cost(){
return this.drink.cost();
}
@Override
public String info(){
return this.drink.info();
}
}
//具体装饰类1
class Milk extends Decorate{
public Milk(Drink drink){
super(drink);
}
@Override
public double cost(){
return super.cost()*4;
}
@Override
public String info(){
return super.info()+"加入了牛奶";
}
}
//具体装饰类2
class Suger extends Decorate{
public Suger(Drink drink){
super(drink);
}
@Override
public double cost(){
return super.cost()*4;
}
@Override
public String info(){
return super.info()+"加入了糖";
}
}
public class DecorateTest{
public static void main(String[] args){
Drink coffee = new Coffee();
Drink suger = new Suger(coffee);
System.out.println(suget.info()+"--->"+suget.cost());
Drink milk = new Milk(coffee);
System.out.println(milk.info()+"--->"+milk.cost());
milk = new Milk(suger);
System.out.println(milk.info()+"--->"+milk.cost());
}
}
字节缓冲流
字节缓冲流使用了 BufferedInputStream&BufferedOutputStream 类。
使用字节缓冲流能够大幅提高字节流的效率。
字节缓冲流也是一个处理流。
【示例】
File sec = new File("a.txt");
InputStream is = null;
BufferedInputStream bis = null;
try{
is = new FileInputStream(src);
bis = new BufferedInputStream(is);
byte[] flush = new byte[1024];
int len = -1;
while((len = bis.read(flush))!= -1){
...
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(is != null){
is.clsoe();
}
if(bis != null){
bis.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
File src = new File("abc.txt");
OutputStream os = null;
try{
os = new BufferedOutputStream(new FileOutputStream(src));
String msg = "Show me the code";
byte[] datas = msg.getBytes();
os.write(datas,0,datas.length);
os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(os != null){
os.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
字符缓冲流
字符缓冲流需要用到 BufferedReader&BufferedWriter 类
【示例】
File src = new File("abc.txt");
Reader reader = null;
try{
reader = new BufferedReader(new FileReader(src));
String line = null;
while((line = reader.readLine())!=null){
System.out.println(line);
}
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(reader!= null){
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】
File dest = new File("abc.txt");
Writer writer = null;
try{
writer = new BufferedWriter(new FileWriter(dest));
writer.append("这是一条神奇的天路哎");
writer.newLine();//另起一行
writer.append("让我们走进了人间天堂");
writer.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer != null){
writer.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
【示例】: 文件拷贝
public void copy(String srcPath,String destPath){
File src = new File(srcPath);
File dest = new File(destPath);
try(BufferedReader br = new BufferedReader(new FileReader(src));
BufferedWriter bw = new BufferedWriter(new FileWriter(dest));){
String line = null;
while((line = br.readLine())!=null){
bw.append(line);
bw.newLine();
}
bw.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
字符转换流
InputStreamReader/InputStreamWriter 是字节流与字符流之间的桥梁,能将字节流转换为字符流,并且能为字节流指定字符集。可处理一个一个字符。
System.in 与 System.out
【示例】
try(BufferedReader reader = new BufferedReader(InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(OutputStreamWriter(System.out));){
String msg = "";
while(!msg.equals("exit")){
msg = reader.readLine();
writer.write(msg);
writer.newLine();
writer.flush();
}
}catch(IOException e){
e.printStackTrace();
}
【示例】
try(InputStreamReader is = new InputStreamReader(new URL("http://www.baidu.com").openStream(),"utf-8");){
InputStream is = new URL("http://www.baidu.com").openStream();
int temp;
while((temp = is.read())!=-1){
System.out.print((char)temp);
}
}
【示例】
try(BufferedReaeder reader = new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream));){
String msg = null;
while((msg = reader.readLine()) != null){
System.out.println(msg);
}
}catch(IOException e){
e.printStackTrace();
}
【示例】
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"utf-8"));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu.html"),"utf-8"));){
String msg = null;
while((msg = reader.readLine()) != null){
writer.write(msg);
writer.newLine();
}
writer.flush();
}catch(IOException e){
e.printStackTrace();
}
数据流
数据流需要使用 DataInputStream&DataOutputStream 类。
数据流会保留原来的数据类型。
PS: 但是要注意,写入数据和读出数据的顺序保持一致
【示例】
ByteArrayOutputStream baos = new ByteOutputStream();
DataOutputStream dos = new DataOutputSteam(baos);
dos.writeUTF("这是一条神奇的天路");
dos.writeint(18);
dos.writeBoolean(false);
dos.writeChar('a');
dos.flush();
byte[] datas = baos.toByteArray();
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(datas));
String msg = dis.readUTF();
int temp = dis.readInt();
boolean flag = dis.readBoolean();
char ch = dis.readChar();
System.out.println(msg);
System.out.println(temp);
System.out.println(flag);
System.out.println(ch);
对象流
对象流需要用到 ObjectInputStream&ObjecOutputStream 类。
序列化:将对象数据存储在数据库,文件或内存中
反序列化:将数据库,文件或内存中的数据转化称为对象
数据的序列化技术也叫作数据的持久化。
【示例】
class Employee implements java.io.Serializable{
private String name;
private double salary;
public Employee(){
super();
}
public Employee(String name, double salary){
super();
this.name = name;
this.salary = salary;
}
public String getName(){
return this,name;
}
public void setName(String name){
this.name = name;
}
public double getSalary(){
return this.salary;
}
public void setSalary(double salary){
this.salary = salary;
}
}
class ObjectTest{
private static void main(String[] args){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BuferedOutputStreawm(baos));
Employee employee = new Employee("张飞",400)
oos.writeObject("明天会更好");
oos.writeObject(new Date());
oos.writeObjcet(employee);
oos.flush();
ObjectInputStream ois = new ObjectInputStream();
Object str = ois.readObject();
Object date = ois.readObject();
Object emp = ois.readObject();
if(str instanceof String){
String strObjcet = (String)str;
}
if(date instanceof Date){
Date dateObject = (Date)date;
}
if(emp instanceof Employee){
Employee empObject = (Employee)emp;
}
}
}
PS: 对于类中不需要序列化的数据,我们可以在添加 transient 语句。
打印流
打印流需要用到 PrintStream 类。
【示例】
// 将信息打印到控制台
PrintStream ps = System.out;
ps.println("打印流");
ps.println(true);
// 将信息打印到文本文件中
ps = new PrintStream(new BufferedOutputStream(new FileOutputStream("a.txt"),true));
ps.println("打印流");
ps.println(true);
// 重定向输出端
System.setOut(ps);
System.out.println("change");
// 重定向回控制台
System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out),true)));
System.out.println("I am backing");
ps.close();
【示例】
PrintWriter pw = new PrintWriter(new BuffereOutputStream(new FileOutputStream("a.txt"),true));
pw.println("打印流");
pw.println(true);
pw.close();
文件序列流
文件序列流可以将文件分成多个小份,并且再将文件合并。文件序列流需要用到 RandomAccessFile 类。RandomAccessFile 类可以随机读取和写入文件。
RandomAccessFile 的两个构造类
方法 | 描述 |
RandomAccessFIle(File file, String mode) | 创建一个随机访问文件流,从 File 参数指定的文件读取,并可以写入 |
RandomAccessFile(String name, String mode) | 创建一个随机访问文件流,以从中指定名称文件读取,并可以写入文件。 |
文件分割
【示例】** :从起始位置读取所有内容
RandomAccessFile raf = new RandomAccessFile(new File("a.txt"),"r");
raf.seek(2);//跳过前两个字符,从第三个字符开始读取文件
byte[] flush = new byte[1024];
int len = -1;
while((len = raf.read(flush))!=-1){
System.out.println(flush,0,len);
}
raf.close();
【示例】 :读取起始位置后指定大小的内容
RandomAccessFile raf = new RandomAccessFile(new File("a.txt"),"r");
int beginPos = 2;
int actualSize = 1026;
raf.seek(beginPos);
byte[] flush = new byte[1024];
int len = -1;
while((len = raf.read(flush))!=-1){
if(actualSize > len){
System.out.println(flush,0,len);
actualSize -= len;
}else{
System.out.println(flush,0,actualSize);
break;
}
}
raf.close();
【示例】 :分块写法
File src = new File("a.txt");
long len = src.length();
int blockSize = 1024;//设定每块的大小
int size = Math.ceil(len*1.0/blockSize);
int beginPos = 0;
int actualSize = (int)blockSize>len ? len:blockSize;
for(int i=0; i<size; i++){
beginPos = i*blockSize();
if(i==size-1){
actualSize = (int)len;
}else{
actualSize = blockSize;
len -= actualSize;
}
}
【示例】
public static void split(int i,int beginPos, int actualSize) throws IOException{
RandomAccessFile raf = new RandomAccessFile(new File("p.png"),"r");
RandomAccessFile raf2 = new RandomAccessFile(new File("dest/" + i + "p.png"),"rw");
raf.seek(beginPos);
byte[] flush = new byte[1024];
int len = -1;
while((len = raf.read(flush))!=-1){
if(actualSize > len){
raf2.write(flush,0,len);
actualSize -= len;
}else{
raf2.write(flush,0,actualSize);
break;
}
}
raf2.flush();
raf.close();
raf2.close();
}
【示例】 :面向对象的具体封装
// 面向对象封装分割后的文件
public class SplitFile{
//源
private File src;
//目的地
private String destDir;
//所有分割后的文件存储路径
private List<String> destPaths;
//每块大小
private int blockSize;
//块数
private int size;
public SplitFile(File src,String destDir){
this(src, destDir, 1024);
}
public SplitFile(File src,String destDir,int blockSize){
this.src = src;
this.destDir = destDir;
this.blockSize = blockSize;
this.destPaths = new ArrayList<String>();
}
//初始化
private void init(){
long len = this.src.length();
this.size = (int)Math.ceil(len*1.0/this.blockSize);
for(int i = 0; i<size;i++){
this.destPaths.add(destDir + i + "-" + this.src.getName());
}
}
public void split() throws IOException{
long len = this.src.length();
int beginPos = 0;
int actualSize = (int)blockSize>len ? len:blockSize;
for(int i=0; i<size; i++){
beginPos = i*blockSize();
if(i==size-1){
actualSize = (int)len;
}else{
actualSize = blockSize;
len -= actualSize;
}
splitDetail();
}
}
private void splitDetail(int i,int beginPos, int actualSize) throws IOException{
RandomAccessFile raf = new RandomAccessFile(this.src,"r");
RandomAccessFile raf2 = new RandomAccessFile(this.destPaths.get(i),"rw");
raf.seek(beginPos);
byte[] flush = new byte[1024];
int len = -1;
while((len = raf.read(flush))!=-1){
if(actualSize > len){
raf2.write(flush,0,len);
actualSize -= len;
}else{
raf2.write(flush,0,actualSize);
break;
}
}
raf2.flush();
raf.close();
raf2.close();
}
}
文件合并
【示例】
public void merg(String destPath){
//输出流
OutputStream os = new BufferedOutputStream(new FileOutputStream(destPath,true));
//输入流
for(int i=0; i<destPaths.size(); i++){
InputStream is = new BufferedInputStream(new FileInputStream(destPaths.get(i)));
byte[] flush = new byte[1024];
int len = -1;
while((len=is.read(flush))!=-1){
os.write(flush,0,len);
}
os.flush();
is.close();
}
os.close();
}
【示例】: 使用 SequenceInputStream 类
// 文件的合并
public void merg(String destPath){
//输出流
OutputStream os = new BufferedOutputStream(new FileOutputStream(destPath,true));
//输入流
Vector<InputStream> vi = new Vector<InputStream>();
SequenceInputStream sis = null;
for(int i=0; i<destPaths.size(); i++){
vi.add(new BufferedInputStream(new FileInputStream(destPaths.get(i))));
}
sis = new SequenceInputStream(vi.elements());
byte[] flush = new byte[1024];
int len = -1;
while((len=sis.read(flush))!=-1){
os.write(flush,0,len);
}
sis.close();
os.close();
}
CommonIO 类
【示例】 :获取文件或者文件夹的大小
long len = FileUtils.sizeof(new File("src/a.txt"));
【示例】 :列出子孙集
Collection<File> files = FileUtils.listFiles(new File("a"),EmptyFileFilter.NOT_EMPTY,DirectorFileFilter.INSTANCE);
for(File file:files){
System.out.ptintln(file.getAbsolutePath());
}
【示例】 :筛选文件后缀
Collection<File> files = FileUtils.listFiles(new File("a"),FileFilterUtils(new SuffixFileFilter("java"),new SuffixFileFilter("txt"),EmptyFileFilter.NOT_EMPTY),DirectorFileFilter.INSTANCE);
【示例】 :文件读取
String msg = FileUtils.readFileToString(new File("empty.txt"),"UTF-8");
System.out.println(msg);
byte[] datas = FileUtils.readFileToByteArray(new File("Empty.txt"));
System.out.println(datas.length);
【示例】 :逐行读取文件
List<String> msgs = FileUtils.readLines(new File("emp.txt"),"UTF-8");
for(String msg:msgs){
System.out.println(msg);
}
LineIterator it = FileUtils.lineIterator(new File("emp.txt"),"UTF-8");
while(it.hasNext()){
System.out.println(it.nextLine());
}
【示例】 :写出内容
FileUtils.write(new File("happy.txt"),"Today is Monday","UTF-8",true);
FileUtils.writeStringToFile(new File("happy.txt"),"Tommorrown is Tuesday","UTF-8",true);
FileUtils.writeByteArrayToFile(new File("happy.txt"),"Tommorrown is Tuesday".getBytes("UTF-8"),true);
// 多行同时写入
List<String> lines = new ArrayList<String>();
lines.add("The First Line");
lines.add("The Second Line");
lines.add("The Third Line");
FileUtils.writeLines(new File("a.txt"),lines,"。",true)
【示例】 :复制文件
FileUtils.copyFile(new File("p.png"),new File("p-copy.png"));
FileUtils.copyFileToDirectory(new File("p.png"),new File("lib"));
//拷贝目录,使被拷贝的目录称为其子目录
FileUtils.copyDirectoryToDirectory(new File("lib1"),new File("lib2"));
//直接拷贝目录内的文件到另一个文件夹
FileUtils.copyDirectory(new File("lib1"),new File("lib3"));
//拷贝 URL 内容
String url = "https://p0.ssl.qhimg.com/dmfd/228_99_75/t01929072af8f9830cf.jpg";
FileUtils.copyURLToFile(new URL(url),new File("a.jpg"));