一、File类
1.1.介绍:
java.io.File类:文件和目录路径名的抽象表示形式。
java把电脑中的文件和文件夹(目录)封装为了一个File类,我们可以使用File类对文件和文件夹进行操作。
1.2、构造器
三种构造器:
- File(String path)
- File(String parentPath,String childPath)
- File(File parentFile,String childPath)
File(String path):
File file1 = new File("heart.text");//相对路径
File file2 = new File("F:\\IDEA\\Workspace(idea)\\JavaSenior.h.text");//绝对路径
相对路径和绝对路径的区别:
相对路劲:相对与某个基准目录的路径,比如在本类中,相对路径就是相较于本类所处的module中文件位置
绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如: C:\xyz\test.txt 代表了test.txt文件的绝对路径。
File(String parentPath,String childPath)
File file3 = new File("F:\\IDEA\\Workspace(idea)","JavaSenior");
File(File parentFile,String childPath)
File file4 = new File(file3,"h.text");
1.3、常用方法:
public string getAbsolutePath(): 获取绝对路径:
File file1 = new File("hello.txt");
System.out.println(file1.getAbsoluteFile());
public String getPath():获取路径(填参时路径)
File file1 = new File("hello.txt");
System.out.println(file1.getPath());
public String getName():获取名称
File file1 = new File("hello.txt");
System.out.println(file1.getName());
public string getParent(): 获取上层文件目路径。若无,返回null
File file1 = new File("hello.txt");
System.out.println(file1.getParent());
public Long length() : 获取文件长度(: 字节数)。不能获取目录的长度
File file1 = new File("hello.txt");
System.out.println(file1.length());
public Long LastModified() : 获取最后一次的修改时间,毫秒值
File file1 = new File("hello.txt");
System.out.println(file1.lastModified());
public string[] List() : 取指定下的所有文件或者文件目录的名称数组
public File[] ListFiles() : 获取指定目录下的所有文件或者文件目录的File数组
public boolean isDirectory(): 判断是否是文件目录
File file = new File("hello.txt");
System.out .println(file.isDirectory());
public boolean isFile(): 判断是否是文件
File file = new File("hello.txt");
System.out.println(file.isFile());
public boolean exists():判断是否存在
File file = new File("hello.txt");
System.out.println(file.exists());
public boolean canRead():判断是否可读
File file = new File("hello.txt");
System.out.println(file.canRead());
public boolean canWrite():判断是否可写
File file = new File("hello.txt");
System.out.println(file.canWrite());
public boolean isHidden(): 判断是否隐藏
File file = new File("hello.txt");
System.out.println(file.isHidden());
创建功能:
public boolean createNewFile() : 创建文件。若文件存在,则不创建,返回false
File file = new File("hi.txt");
System.out.println(file.createNewFile());
删除:public boolean delete(): 删除文件或者文件夹删除注意事项:
Java中的删除不走回收站
要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
File file = new File("hi.txt");
System.out.println(file.delete());
一个小练习
//练习
@Test
public void test5(){
//1.判断指定目录下是否有后缀名为.jpg的文件,如果有,就输出该文件名称
File file = new File("F:\\IDEA\\Workspace(idea)\\JavaSenior\\IOstream");
String[] list = file.list();
for (String f:list){
if (f.endsWith("jpg")){
System.out.println(f);
}
}
System.out.println("==============");
//遍历指定目录所有文件名称,包括子文件目录中的文件
// 拓展1:并计算指定目录占用空间的大小
// 拓展2: 删除指定文件目录及其下的所有文件
File file1 = new File("F:\\Test");
printSubFile(file1);
}
public static void printSubFile(File file){
File[] files = file.listFiles();
for (File f:files) {
if (f.isDirectory()){
printSubFile(f);
}else {
System.out.println(f.getAbsoluteFile());
}
}
}
二、Java.io.file类的使用
2.1、Io、文件流、缓冲流的体系
2.2、IO流的体系:
三、字符流
3.1、使用FileReader读取文本文件
@Test
public void test2() {
FileReader fr = null;
try {
//1.获取需要读取的文件
File file = new File("src\\hello");
//2.选择所需要的流
fr = new FileReader(file);
//3.读取文件
//两种正确的写法
//方式一:
char[] c = new char[5];//根据选择的流来创建相应的数组
int len;//用来记录读取了几个数
while ((len = fr.read(c)) != -1) {//read():读取文件中的字符,返回一个字符 如果读完了,返回一个-1
for (int i = 0; i < len; i++) {
System.out.print(c[i]);
}
System.out.print(len);
// //方式二:
// String str = new String(c,0,len);
// System.out.print(str);
}
//两种相对应错误的写法
//一:
// while (len = fr.read(c)!=-1){
// System.out.println(len);
// for (int i = 0; i < c.length; i++) {//读取字符写进数组时,将新读取的字符在对应的位置覆盖原有的字符
// //当i<c.length 会将数组内5个数全部输出出来,就变成了helloWorld123!
// System.out.print(c[i]);
// }
// }
//二:
// String str = new String(c);//直接输出了
// System.out.println(str);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//关闭流
try {
fr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
read只能读取一个字符,当我们需要读取文本的一整行时,调用readLine()。
3.2、FileWriter输出文本文件:
注意: 使用FileWriter输入文件
说明:输出操作,对应的File是否存在的问题:
如果不存在,则在输出过程中,会自动创建此文件
如果存在:
如果调用的构造器为 FileWriter(file,false) /FileWriter(file),则将原有的文件覆盖
如果调用的构造器为 FileWriter(file,true),则在原有的文件的基础上追加要输出的内容
@Test
public void test3() {
FileWriter fw = null;
try {
//1.创建文件
File file = new File("hello.txt");
//2.根据需要选择对应的流
fw = new FileWriter(file, false);
//3.输出操作
fw.write("I want to make money!");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//4.关闭流
try {
if (fw != null) {
fw.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
3.3、练习:测试将一个文件读取然后写进另一个文件
@Test
public void test4() {
FileReader fr = null;
FileWriter fw = null;
try {
//1.指明需要读取的文件 和 需要写入的文件路径
File srcFile = new File("src\\hello");
File writeredFile = new File("hello3.txt");
//2.创建输入流 和 输出流
fr = new FileReader(srcFile);
fw = new FileWriter(writeredFile, true);
//3.读取和输出操作
int len;
while ((len = fr.read()) != -1) {
fw.write(len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//4.关闭流
try {
if (fr != null && fw != null) {
fr.close();
fw.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
四、字节流
4、使用FileInputStream和FileOutputStream将一个文件读取到另一个文件中:
@Test
public void testCopy(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1.提供所需要读取的文件 和 需要写入的文件
File srcFile = new File("a.jpg");
File destFile = new File("史迪仔.jpg");
//2.选取所需要的流
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
//3.读取和写入过程
int len;
byte[] buffer = new byte[5];
while((len = fis.read(buffer)) != -1){
fos.write(buffer);
}
System.out.println("执行成功");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fis != null){
//4.关闭流
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}if (fos != null){
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
五、缓冲流
5.1、作用
提高流的读取、写入的速度提高读写速度的
原因: 内部提供了一个缓冲区
5.2、测试
@Test
public void test1(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.提供 所需要读取 和 写入的文件
File srcFile = new File("a.jpg");
File destFile = new File("史迪仔2.jpg");
//2.创建流
//2.1、创建字节流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2、创建缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.读取和写入过程
int len;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(bis != null){
//4.关闭流:因为在关闭外层的同时,也会将内层关闭,所以只需写关闭外层的close
try {
bis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} if(bos != null){
try {
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
六、转化流
6.1、两种转化流:
- InputStreamReader: 将输入的字节流转换为输入的字符流
- OutputStreamWriter: 将输出的字符流转换为输出的字节流
6.2、测试
@Test
public void test1(){
java.io.InputStreamReader isr = null;
try {
FileInputStream fis = new FileInputStream("hello.txt");
isr = new java.io.InputStreamReader(fis,"UTF-8");
//参数2说明:指定字符集进行转换,默认为UTF-8,具体需要使用哪个字符集,根据文件存的时候使用哪个字符集
int len;
char[] c = new char[1024];
while((len = isr.read(c)) != -1){
for (int i = 0; i < len; i++) {
System.out.print(c[i]);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
isr.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
七、对象流
7.1、作用
对象流 ObjectInputStream 、 ObjectOutputStream
用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以将java中的对象写入到数据源中,也能把对象从数据源中恢复过来
7.2、序列化、反序列化:
序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
对象序列化机制—>允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,
或通过网络将这种二进制流传输到另一个网络节点。
//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
- 注意:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
对于定义类的序列化和反序列化:
- 要求自定义的类必须实现Serializable接口
- 自定义类必须提供一个序列化编号:serialVersionUID,用于识别
- 类中的自定义类类型的属性也必须是实现Serializable
7.3、测试:
先自定义一个Person类,并实现Serializable接口和提供一个序列化编号serialVersionUID
class Person implements Serializable{
public static final long serialVersionUID = 421211212121232L;
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
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{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
序列化和反序列化简单过程
@Test
public void testOutputStream(){
//对象的序列化:
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
oos.writeObject(new String("我爱中国!"));
oos.flush();
oos.writeObject(new Person("张廷",21));
oos.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (oos != null){
try {
oos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
@Test
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object o = ois.readObject();
Person p = (Person) ois.readObject();
System.out.println(p);
System.out.println(o.toString());
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (ois !=null){
try {
ois.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
八、随机存取文件流
8.1、说明
随机存取文件流
继承于Object类,实现了DataInput 和 DataOutput接口,也就意味着这个流可读也可写
如果RandomAccesFile作为输出流时, 写出到的文件
如果不存在,则在执行过程中自动创建
如果写出到的文件存在,则会对原有文件内容进行覆盖。 (默认情况下,从头覆盖)
8.2、测试
@Test
public void test1(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile("a.jpg","r");//参数说明 String mode :"r" 表示只可读
raf2 = new RandomAccessFile("史迪仔1.jpg","rw");// "rw" 表示可读也可写
byte[] buffer = new byte[1024];
int len;
while((len = raf1.read(buffer) )!= -1){
raf2.write(buffer);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (raf1!=null){
try {
raf1.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (raf2!=null){
try {
raf2.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
测试RandomAccessFile void seek():方法
@Test
public void test2(){
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("hello.txt", "rw");
raf.seek(12);//将角标置到 15 的位置
raf.write("more".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if (raf != null){
raf.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
利用seek方法实现本文文字插入操作
// 实现插入操作 思路:先将要插入位置的后面内容保存起来,然后再将角标至于要插入的位置,将要插入的内容写入,最后再将之前保存起来的内容写入
@Test
public void test3(){
RandomAccessFile rw = null;
try {
rw = new RandomAccessFile("test.txt", "rw");
StringBuilder builder = new StringBuilder((int) new File("test.txt").length());
int len;
byte[] buffer = new byte[20];
while((len = rw.read(buffer)) != -1){
builder.append(new String(buffer,0,len));
}
rw.seek(3);//将角标至于3的位置
rw.write("zt".getBytes());
rw.write(builder.toString().getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
rw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
九、其他流的使用:
9.1、标准的输入流、输出流
9.1.1、说明
标准的输入、输出流:
System.in:标准的输入流,从键盘输入
System.out:标准的输出流,从控制台输出
9.1.2、测试
public static void main(String[] args) {
BufferedReader reader = null;
try {
java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);
reader = new BufferedReader(isr);
while(true){
String data = reader.readLine();
if ("e".equals(data) || "exit".equals(data)){
System.out.println("程序结束!");
break;
}
String s = data.toUpperCase();
System.out.println(s);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}