File类
说明:文件和目录路径名的抽象表示形式。
一、常量:
1、File.pathSeperator:路径分隔符 (;)
2、File.separator:文件名分隔符 (Windows是\,非Windows是/,为了达到跨平台目的,要用静态常量)
二、路径表示形式:
import java.io.File;
public class Demo01 {
public static void main(String[] args) {
//(1) 直接法,注意使用双斜杠(单斜杠表转义),此方法不推荐使用
String path = "F:\\others\\1.txt";
//(2) 使用常量分隔符表示,跨平台,适合动态生成时使用,如果是定值,也不推荐使用
path = "F:"+File.separator+"others"+File.separator+"1.txt";
//(3) 使用反斜杠,可在其他平台使用,推荐使用!
path = "F:/others/1.txt";
}
}
三、构造File对象:
相对路径与绝对路径
public class Demo02 {
public static void main(String[] args) {
//相对路径
String parentPath = "F:/others";
String name = "1.jpg";
File src = new File(parentPath,name);
src = new File(new File(parentPath),name);
//绝对路径
src = new File("F:/others/1.txt");
//没有盘符?以目前的工程路径构建
src = new File("2.jpg");
System.out.println(src.getPath());//相对路径
System.out.println(src.getAbsolutePath());//绝对路径
}
}
四、常用方法:
1、获取文件名、路径名
- getName():文件名、路径名
- getPath():路径名(如果是绝对路径,返回完整路径,否则相对路径)
- getAbsoluteFile():绝对路径File对象
- getAbsolutePath():绝对路径名
- getParent():父目录,返回上一级目录,如果是相对路径的父目录,返回null
2、判断信息
- exists():是否存在
- canWrite():是否可读,不仅可读写文件,还可读写路径
- canRead():
- isFile():是否是文件,如果文件不存在或File不是文件名,返回false
- isDirectory():是否是路径
- isAbsolute():消除平台差异,以盘符开头就是绝对路径,相对路径以“/”开头
3、长度
- length():文件大小的字节数,如果是文件夹或文件不存在,则为0
4、创建、删除
- createNewFile():成功返回true,如果路径不存在或同名文件存在, 则返回false
- delete():删除成功返回true,失败false
- createTempFile():创建临时文件,返回file
5、操作目录
- mkdir():创建目录,成功返回true,如果父目录不存在或目录已存在,则返回false
- mkdirs():创建目录,如果父目录链不存在,一同创建
- list():子文件或子目录的名字,返回String数组
- listFiles():子文件或子目录的File对象,返回File数组,还可以使用过滤器FileFilter
- listRoots():根目录
IO流
一、原理与概念
1、流:流动、流向,从一段移动到另一端,源头与目的地
数据源:程序与文件、数组、网络连接、数据库,以程序为中心
2、IO流的分类
- 按流向:输入流与输出流
- 按数据:字节流(二进制,可处理一切文件)与字符流(文本文件,只能处理纯文本)
- 按功能:节点流(包裹源头)与处理流(增强功能,提高性能)
3、字节流与字符流
(1)字节流
- 输入流:InputStream 抽象类
- 方法:reader(byte[] b)、reader(byte[] b, int off, int len)、close()
- FileInputSteam
- 输出流:OutputStream 抽象类
- 方法:write(byte[] b)、write(byte[] b, int off, int len)、flush()、close()
- FileOutputStream
(2)字符流
- 输入流:Reader
- 方法:reader(char[] cbuf)、reader(char[] cbuf, int off, int len)、close()
- FileReader()
- 输出流:Writer
- 方法:write(char[] cbuf)、write(char[] cbuf, int off, int len)、flush()、close()
- FileWriter()
二、字节流
1、读取文件
- 建立联系:File对象 源头
- 选择流:文件输入流 InputStream FileInputStream
- 操作:
- (1)定义数组大小:byte[] car = new byte[1024]; read 读取大小
- (2)输出
- 释放资源:关闭
public class Demo01 {
public static void main(String[] args) {
//1、建立联系:File对象
File src = new File("f:/others/test/2.txt");
//2、选择流
InputStream is = null;//提升作用域
try {
is = new FileInputStream(src);
//3、读取
byte[] max = new byte[10];//缓冲数组
int len = 0;//接收实际读取的大小
//循环读取,读取结束返回-1
while(-1!=(len=is.read(max))) {
//输出:将字节数组转成字符串
String info = new String(max,0,len);
System.out.println(info);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
}finally {
//4、释放资源
if(null!=is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭文件输入流失败");
}
}
}
}
}
2、写出文件
- 建立联系:File对象 目的地
- 选择流:文件输出流 OutputStream FileOutputStream
- 操作:
- (1)write() + flush()
- (2)输出
- 释放资源:关闭
public class Demo02 {
public static void main(String[] args) {
//1、建立联系
File dest = new File("f:/others/test/2.txt");
//2、选择流
OutputStream os = null;
try {
//true-->追加,false-->覆盖
os = new FileOutputStream(dest,true);
String str = "添加内容";
//字符串转字节数组
byte[] data = str.getBytes();
os.write(data);
//强制刷新出去
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("文件未找到");
} catch (IOException e) {
e.printStackTrace();
System.err.println("文件写出失败");
} finally {
//4、释放资源
if(null!=os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
System.err.println("关闭输出流失败");
}
}
}
}
}
- 建立联系:File对象 源头 目的地
- 选择流:文件输入流 InputStream FileInputStream、文件输出流 OutputStream FileOutputStream
- 操作:
- (1)定义数组大小:byte[] car = new byte[1024]; int len = 0;
- (2)while(-1 != ( len = 输入流.read( flush ) ) ){
- 输出流.write( flush , 0 , len )
- }
- (3)输出流.flush
- 释放资源:关闭
public class Demo03 {
public static void main(String[] args) throws IOException {
//1、建立联系
File src = new File("F:/others/test/2.txt");
File dest = new File("F:/others/test/1.txt");
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(src);
os = new FileOutputStream(dest);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte []flush = new byte[1024];
int len = 0;
while(-1 != (len = is.read(flush))) {
os.write(flush, 0, len);
}
os.flush();
os.close();
is.close();
}
}
4、拷贝文件夹
- 递归查找子孙级文件、文件夹
- 判断是文件夹还是文件,文件夹需要创建
public class Demo04 {
public static void main(String[] args) {
copy("f:/others/test/1","f:/others/test2");
}
public static void copy(String srcPath,String destPath) {
File src = new File(srcPath);
File dest = new File(destPath);
try {
copy(src,dest);
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取失败");
}
}
public static void copy(File src,File dest) throws IOException {
if(src.isDirectory()) {
//在 父目录dest 下创建 子目录src.getName()
dest = new File (dest,src.getName());
}
if(src.isFile()) {
Demo03.copyFile(src, dest);
}else if(src.isDirectory()) {
//dest目录存在
dest.mkdirs();
for(File sub:src.listFiles()) {
copy(sub,new File(dest,src.getName()));
}
}
}
}
三、字符流
1、拷贝纯文本文件
- 递归查找子孙级文件、文件夹
- 判断是文件夹还是文件,文件夹需要创建
public class Demo01 {
public static void main(String[] args) {
try {
copyChar("f:/others/1.txt","f:/others/test/1.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyChar(String srcPath,String destPath) throws IOException {
File src = new File(srcPath);
File dest = new File(destPath);
Reader reader = null;
Writer wr = null;
reader = new FileReader(src);
wr = new FileWriter(dest);
//读取操作
char[] flush = new char[1024];
int len = 0;
while(-1 != (len = reader.read(flush))) {
wr.write(flush, 0, len);
}
wr.flush();//强制刷出
//先打开的后关闭
wr.close();
reader.close();
}
}
四、处理流
特点:增强功能、提高性能。写在节点流之上。
1、缓冲流
- 字节缓冲流:BufferdInputStream BufferedOutputStream
InputStream is = null;
OutputStream os = null;
is = new BufferedInputStream(new FileInputStream(src));
os = new BufferedOutputStream(new FileOutputStream(dest));
- 字符缓冲流:BufferedReader BufferedWriter
BufferedReader reader = null;
BufferedWriter wr = null;
reader = new BufferedReader(new FileReader(src));
wr = new BufferedWriter(new FileWriter(dest));
//读取操作(新增)
String line = null;
while(null != (line = reader.readLine())) {
wr.write(line);
wr.newLine();
}
2、转换流
字节流转换为字符流:InputStreamReader
BufferedReader br = new BufferedReader( //缓冲字符流优点是可以按行读取
new InputStreamReader( //为避免乱码,字符流要转换为字节流
new FileInputStream(
new File("f://others","utf-8")//指定解码集
)
)
);
3、重点流关系图
五、节点流
1、字节数组 节点流
- 输入流:ByteArrayInputSream read、close
- 输出流:ByteArrayOutputStream write、toByteArray
/**
* 字节数组流
* 数组的长度有限,数据量不会很大
*
* 文件内容不用太大
* 1、文件 --程序--> 字节数组
* 2、字节数组 --程序--> 文件
*
*/
public class Demo01 {
public static void main(String[] args) throws IOException {
read(write());
}
public static byte[] write() throws IOException {
//目的地
byte[] dest;
//选择流
ByteArrayOutputStream bos= new ByteArrayOutputStream();
//写出
String msg = "123456";
byte[] info = msg.getBytes();
bos.write(info,0,info.length);
//获取数据
dest = bos.toByteArray();
//释放资源
bos.close();
return dest;
}
public static void read(byte[] src) throws IOException {
//数据源传入
//选择流
InputStream is = new BufferedInputStream(
new ByteArrayInputStream(src)
);
byte[] flush = new byte[1024];
int len = 0;
while(-1!=(len=is.read(flush))) {
System.out.println(new String(flush,0,len));
}
is.close();
}
}
- 与文件对接
public class Demo02 {
public static void main(String[] args) throws IOException {
toFileFromByteArray(getBytesFromFile("f://others/test/1.txt"),"f://others/test/2.txt");
}
public static void toFileFromByteArray(byte[] src, String destpath) throws IOException {
InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(destpath)));
byte[] flush = new byte[1024];
int len = 0;
while(-1!=(len=is.read(flush))) {
os.write(flush, 0, len);
}
os.flush();
os.close();
is.close();
}
public static byte[] getBytesFromFile(String srcpath) throws IOException {
File src = new File(srcpath);
InputStream is = new BufferedInputStream(new FileInputStream(src));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] dest = null;
byte[] flush = new byte[1024];
int len = 0;
while(-1!=(len=is.read(flush))) {
bos.write(flush,0,len);
}
bos.flush();
dest = bos.toByteArray();
bos.close();
is.close();
return dest;
}
}
- 文件的分割与合并 RandomAccessFile(File file,String mode)、方法seek(beginPos)
六、处理流
1、基本类型+String 保留数据+类型
- 输入流:DataInputStream
- 输出流:DataOutputStream
(新增方法不能发生多态)
public class Demo01 {
public static void main(String[] args) throws IOException {
write("f://others/test/2.txt");
read("f://others/test/2.txt");
}
/**
* 从文件读取数据+类型
* @throws IOException
*/
public static void read(String destpath) throws IOException {
DataInputStream dis = new DataInputStream(
new BufferedInputStream(
new FileInputStream(new File(destpath))));
//操作读取数据顺序与写出一致,不一致数据可能存在问题
double num1 = dis.readDouble();
long num2 = dis.readLong();
String str = dis.readUTF();
dis.close();
}
/**
* 数据+类型输出到文件
* @throws IOException
*
*/
public static void write(String destpath) throws IOException {
double point = 2.5;
long num = 100L;
String str = "123";
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(new File(destpath))));
//操作写出的顺序,为读取准备
dos.writeDouble(point);
dos.writeLong(num);
dos.writeUTF(str);
dos.close();
}
}
七、装饰设计模式:相当于是一个扩音器
类与类之间的关系:
- 依赖:形参 | 局部变量
- 关联:属性,聚合:属性整体与部分不一致的生命周期,组合:属性整体与部分一致的生命周期
- 继承:父子类关系
- 实现:接口与实现类关系