Java11 文件操作和io流

文件操作和IO流

在这里插入图片描述

磁盘操作

File类

java.io.File 类是java提供的针对磁盘中文件和目录对象的一个类。代表操作系统的文件(文件、文件夹)

创建file对象
1.public File(String pathname): 以pathname为路径创建File对象,可以是绝对路径或者相对路径

2.public File(String parent,String child) 以parent为父路径,child为子路径创建File对象

3.public File(File parent,String child) 根据一个父File对象和子文件路径创建File对象
小贴士: 
1.一个File对象代表指向硬盘中的一个文件或者目录路径(举例,只代表此路径,不代表里面的内容。举例:地址不是房子,File对象指向地址,不是文件本身) 
2.无论该路径下是否存在文件或者目录,都不影响File对象的创建。
文件操作
获取文件信息
public String getName() :获取文件的名称,带后缀

public long length() :获取文件长度(即:字节数---真实的大小)。不能获取目录的长度--仅表示当前操作系统为保存目录所涉及的长度。

public long lastModified() :获取最后一次的修改时间,毫秒值 使用new Date(f1.lastModified());// 返回的是当天时间

public String getAbsolutePath():获取文件的绝对路径 

public String getPath() :获取路径,返回定义文件时使用的路径     

public String getCannoicalPath() 获取规范

public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组---注意返回类型
public File[] listFiles() :获取指定目录下的所有文件或者目录的File数组----返回时File

注意:
1.在使用时要确认其是一个目录(如果是文件返回为null,如果没有权限访问此目录返回也是null2.当文件对象代表一个空文件夹时 返回一个长度为0的数组

3.当文件对象是一个有内容的文件夹时,将里面所有文件和文件夹的路径放在File数组中返回

4.单文件对象是一个有隐藏文件的文件夹时,将里面所有文件和文件夹的路径放入File数组中放回,包含隐藏文件
判断文件
public boolean exists() :判断是否存在

public boolean isDirectory():判断是否是目录
public boolean isFile() :判断是否是文件
 
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏
// 文件夹和文件存在
File file1 = new File("E:\\apesourcefile\\Test");
File file2 = new File("E:\\apesourcefile\\Test\\a.txt");
// 文件夹和文件不存在
File file3 = new File("E:\\apesourcefile\\Test1");
File file4 = new File("E:\\apesourcefile\\Test\\a1.txt");

//		public boolean exits():判断是否路径实际存在
//		public boolean isFile():判断是否为文件
//		public boolean isDirectory():判断是否为目录
System.out.printf("%s是否存在,是否为文件%s,是否为文件夹%s\n", file1.getName(), file1.exists(), file1.isFile(),
                  file1.isDirectory());
System.out.printf("%s是否存在,是否为文件%s,是否为文件夹%s\n", file2.getName(), file2.exists(), file2.isFile(),
                  file2.isDirectory());
System.out.printf("%s是否存在,是否为文件%s,是否为文件夹%s\n", file3.getName(), file3.exists(), file3.isFile(),
                  file3.isDirectory());
System.out.printf("%s是否存在,是否为文件%s,是否为文件夹%s\n", file4.getName(), file4.exists(), file4.isFile(),
                  file4.isDirectory());
删除文件
public boolean delete():
删除此抽象路径名表示的文件或者文件夹

注意:delete方法只删除文件和空文件夹,是直接删除不走回收站
public boolean delete()
//		只能删除文件或者空文件夹
File file1 = new File("E:\\apesourcefile\\Test");
File file2 = new File("E:\\apesourcefile\\Test\\空文件夹1");
File file3 = new File("E:\\apesourcefile\\Test\\aa.txt");

System.out.printf("%s删除是否成功%s\n", file1.getName(), file1.delete());
System.out.printf("%s删除是否成功%s\n", file2.getName(), file2.delete());
System.out.printf("%s删除是否成功%s\n", file3.getName(), file3.delete());
创建文件
public boolean createNewFile()
创建文件。若文件存在,则不创建,返回false

public boolean mkdir() :
创建文件目录。如果此文件目录存在,就不创建了。
如果此文件目录的上层目录不存在,也不创建。

public boolean mkdirs() :
创建文件目录。如果上层文件目录不存在,一并创建
// createNewFile创建文件(路径一定要存在,只有文件可以不存在)
// 若文件存在则不创建,返回false,如果不存在则创建,返回true
File file1 = new File("E:\\apesourcefile\\Test\\b.txt");
boolean b1 = file1.createNewFile();
System.out.println("文件是否创建成功" + b1);

// mkdir()
// 创建目录,如果父级目录不存在,也不能创建成功
// 创建目录,如果此目录不存在,则创建,如果存在则不能创建
File file2 = new File("E:\\apesourcefile\\Test1\\空文件夹");
boolean b2 = file2.mkdir();
System.out.println("目录是否创建成功" + b2);

// mkdirs() 创建目录,如果上层的目录不存在,则一并开始创建
boolean b3 = file2.mkdirs();
System.out.println("创建多层目录是否成功:" + b3);

Files工具类

字符操作
readAllLine(Path path)  按行读取指定路径中的内容
Path write(Path path, List<String> list) 写入字节到
字节操作
byte[] readAllBytes(Path path)  读取文件中的所有字节。 
Path write(Path path, byte[] bytes) 写入字节到指定的路径
遍历目录(非递归)
walkFileTree(Path start,  FileVisitor<? super Path> visitor)

IO流

 I 表示Input ,把硬件文件的数据读入到内存的过程,称之输入,负责读
 O表示output ,把内存中的数据写出到硬盘文件的过程 称之输出 负责写

字节操作(字节流)

操作的最小单元:byte-----包含音频视频图片等

输出流:InputStream(读)
方法:
int read()

读取输入流的下一个字节
读取一个8位的字节,把它转化为0-255之间的整数,并返回这个整数。
读到末尾,返回-1,遇到-1代表文件中的数据已经被读取完毕
int read(byte b[ ])

每次读取N个字节,存入byte[ ]字节数组中
int的返回值是读取字节的长度
读到末尾,返回-1
public void close() 

关闭此输入流,并释放与此流相关联的任何系统资源。 
原因:在IO流进行操作时,当前IO流回占用到一定的内存,由于系统资源宝贵,因此在进行IO操作结束后,调用close方法关闭流,从而释放资源
实现类

FileInputStream类

基于磁盘中字节内容的输入流

构造方法
FileInputStream(File file);   通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
FileInputStream(String name);     通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。

BufferedInputStream类

带有缓冲区的输入流
作用:没有缓冲区,就好像逛超市没有推车,一次只拿一样东西区结账,缓冲区可以暂时放一堆数据到满为止

ObjectInputStream类

对象输入流,进行反序列化操作
输出流:OutputStream(写)
方法:
write(int b)

写入一个字节
write(byte b[])

把这个b字节数组中的所有数据写到关联的设备中(设备包括文件、网络或者其他任何地方)。
write(byte b[], int off, int len)

把数组b字节中的数据从下标off位置开始往出写,共计写len个。
public void close() 

关闭此输出流并释放与此流相关联的任何系统资源。
close方法,当完成流的操作时,必须调用此方法,释放系统资源。
实现类:

FileOutStream类

基于磁盘中字节内容的输出流

BufferedOutStream类

带有缓冲区的输入流

ObjectOutputStream类

对象输出流,进行序列化操作

字符操作(字符流)

操作的最小单元:txt文本文件或者java文件
输出流:Writer(写)
方法
void write(int data);//写出一个字符的数据

void write(char[] array);

void write(char[] array,int offset,int len);

void write(String str);

void write(String str,int offset,int len);

void flush(); 刷新输出流并强制任何缓冲数据的字符被输出到目标位置

void close();//调用close方法的时候,底层会把缓冲区中的数据写出到目标位置。
子类

FileWriter类构造方法

public FileWriter(String path);

public FileWriter(File path);

public FileWriter(String path,boolean append);

public FileWriter(File path,boolean append);

BufferedWriter类方法

void write(String str)  写入一整行

void newLine( )     
创建新行,输出换行符(根据操作系统不同,输出不同的换行符,windows是\r\n,LinuxMac OS是\n)
输入流:Reader(读)
方法
int read()读取一个字符的数据,如果没有数据则返回-1

int read(char buf[])  读取数据存入char数组中,返回读取的长度,如果没有数据则返回-1

void close();   关闭此流并释放与此流相关联的任何系统资源。
子类

FileReader类构造方法

public FileReader(String path);

public FileReader(File path);

BufferedReader类方法

String readLine( )
读取一整行
读取至末尾,返回null

序列化和反序列化

注意事项:

1.序列化对象一定要是实现Serializable接口

2.序列化对象的成员变量也一定要实现可序列化,实现Serializable接口

3.反序列化类文件信息要和序列化保持一致,不然会抛出异常

如果进行序列化和反序列化的时候类文件不能保持一致,写一个静态常量serialVersionUID

4.如果不想成员变量被序列化,需要加关键字transient

public class Demo01 {
	public static void main(String[] args) {
		// 序列化: 对象-->二进制字节数组
		Person p1 = new Person("赵文瑜", 21);
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"))) {
			oos.writeObject(p1);//将指定的对象以流的方式写到文件中
            System.out.println("输出结束");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Demo02 {
	public static void main(String[] args) {
		//反序列化操作:二进制数据-->对象
		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"))) {
		     Object object = ois.readObject();
		     if(object instanceof Person) {
		    	 Person p1 = (Person)object;
		    	 System.out.println(p1.name);
		    	 System.out.println(p1.age);
		     }
		     System.out.println(object);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

序列化和反序列化

package apesource.knowledge03.序列化;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Demo03 {
	public static void main(String[] args) {
//		writeObj();
		readObj();
	}

	public static void writeObj() {
		// 序列化:
		Person p1 = new Person("陈博文", 23, new Money("美元", 1093944));
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f.txt"))) {
			oos.writeObject(p1);
			System.out.println("写出结束");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//反序列
	public static void readObj() {
		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("f.txt"))) {
			Object obj = ois.readObject();
			if(obj instanceof Person) {
				Person p1 = (Person)obj;
				System.out.println(p1.mon);
				System.out.println(p1.name);
				System.out.println(p1.age);
			}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
import java.io.Serializable;

public class Person implements Serializable{
	private static final long serialVersionUID = -2466301751581554679L;
	public transient String name; //序列化时不序列化此成员变量
	public int age;
	public transient Money mon;
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person(String name, int age, Money mon) {
		super();
		this.name = name;
		this.age = age;
		this.mon = mon;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
}
package apesource.knowledge03.序列化;

import java.io.Serializable;

public class Money implements Serializable{
	private static final long serialVersionUID = 5147524361315819540L;
	public String bz;
	public int money;
	
	public Money(String bz, int money) {
		super();
		this.bz = bz;
		this.money = money;
	}
	@Override
	public String toString() {
		return "Money [bz=" + bz + ", money=" + money + "]";
	}
}

Properties类读取配置文件

//setProperty(key,value);
//getProperty(key)
//getProperty(key,defaultValue)
//stringPropertyNames()//所有键的集合

//store(OutputStraem os,String comment)//将properties输出流加载起来
//store(Writer w,String comment)

//load(Reader reader)
//load(InputStream is)
package day24_Files工具类;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Demo01 {
	public static void main(String[] args) throws IOException {
		// 写出字符操作path=路径,bytes=字节内容
		// Path write(Path path,byte[] bytes) 写入字节到指定的路径
		byte[] bytes = "我本将心照明月,奈何明月照沟渠".getBytes();
		Files.write(new File("files01.txt").toPath(), bytes);

		// 写出字符操作
		// write(Path path,List<String> list) 写入字符到指定的路径
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 100; i++) {
			list.add(UUID.randomUUID().toString());
		}
		Files.write(new File("files02.txt").toPath(), list);
	}
}
package day24_Properties;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

public class Demo02 {
	public static void main(String[] args) {
		Properties p1 = new Properties();
		p1.setProperty("张三", "18");
		p1.setProperty("李四", "19");
		p1.setProperty("王五", "20");

		try (Writer w1 = new FileWriter("info.txt")) {
			p1.store(w1, "helloworld");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
package day24_Properties;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

public class Demo03 {
	public static void main(String[] args) {
		Properties p1 = new Properties();
		try (Reader r1 = new FileReader("info.txt")) {
			p1.load(r1);
			System.out.println(p1.getProperty("李四"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
package day24_Properties;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class Demo04 {
	public static void main(String[] args) {
		try (InputStream is = Demo04.class.getResourceAsStream("/config.properties")) {
			Properties p1 = new Properties();// 准备属性集
			p1.load(is);

			// 获取所有的键
			Set<String> set = p1.stringPropertyNames();

			// 迭代器遍历
			Iterator<String> it = set.iterator();
			while (it.hasNext()) {
				String key = it.next();
				String value = p1.getProperty(key);
				System.out.println(key + "_" + value);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

属性集

//Properties
//setProperty(key, value)保存一对属性
//getProperty(key)
//getProperty(key,defaultValue)
//stringPropertyNames()//所有键的集合

//store(OutpuStream os,String comment)  //将properties和输出流加载起来
//store(Writer w,String comment)

//load(Reader reader)
//load(InputStream is)
import java.io.Reader;
import java.util.Properties;
import java.util.Set;

//Properties
//setProperty(key, value)保存一对属性
//getProperty(key)
//getProperty(key,defaultValue)
//stringPropertyNames()//所有键的集合

//store(OutpuStream os,String comment)  //将properties和输出流加载起来
//store(Writer w,String comment)

//load(Reader reader)
//load(InputStream is)
public class Demo01 {
	public static void main(String[] args) {
		// 创建一个空的属性列表
		Properties p1 = new Properties();
		Object oldValue1 = p1.setProperty("姓名", "张三丰");
		Object oldValue2 = p1.setProperty("年龄", "29");
		Object oldValue3 = p1.setProperty("姓名", "赵文瑜");
//		System.out.println(oldValue1);
//		System.out.println(oldValue2);
//		System.out.println(oldValue3);
		System.out.println(p1);
		//得到键对应的值:如果此键不存在,返回null
//		String string = p1.getProperty("姓名111");
//		System.out.println(string);
		//得到键对应的值,如果此键不存在,给默认值
		String string = p1.getProperty("姓名111","0000");
		System.out.println(string);	
		//获取键对应的值
		Set<String> set1 =  p1.stringPropertyNames();
		for (String str : set1) {
			System.out.println(str+"_"+p1.getProperty(str));
		}
	}
}

属性集写入

package apesource.knowledge03.属性集;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

public class Demo02 {
	public static void main(String[] args) {
		Properties p1 = new Properties();
		p1.setProperty("王文茜", "21");
		p1.setProperty("陈博文", "23");
		p1.setProperty("赵文瑜", "76");
		try (Writer w1 = new FileWriter("info.txt")) {
			p1.store(w1, "helloworld");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}

属性集读取

package apesource.knowledge03.属性集;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

public class Demo03 {
	public static void main(String[] args) {
		Properties p1 = new Properties();
		try (Reader r1 = new FileReader("info.txt")) {
		   p1.load(r1);//将输入流和p1对象进行加载
		   System.out.println(p1.getProperty("赵文瑜"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.InterfaceAddress;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class Demo04 {
	public static void main(String[] args) {
		// classpath路径下的文件读取
		try (InputStream is = Demo04.class.getResourceAsStream("/config.properties")) {
			Properties p1 = new Properties();// 准备属性集
			p1.load(is);// 通过p1对象加载文件
			// 获取所有的键
			Set<String> set = p1.stringPropertyNames();
			// 使用迭代器进行遍历
			Iterator<String> it = set.iterator();
			while(it.hasNext()) {
				String key = it.next();
				String value = p1.getProperty(key);
				System.out.println(key+"_"+value);
			}		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

  • 24
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值