Java基础 -- 呕心沥血的JavaIO流篇笔记

File类

简介:java.io.File类,用来描述文件/目录信息的,例如:通过File类可以获取文件名称、大小、修改时间等信息。但是不能访问文件的内容

java.io.File类常用方法:

File(String filename),构造方法,根据参数路径构造文件对象
boolean exists() - 用于判断文件或目录的名称
String getName() - 用于获取文件的名称
long length() -用于获取文件的大小
String getAbsolutePath() - 用于获取抽象路径的绝对路径信息并返回
long lastModified() -用于获取最后一次修改时间
boolean delete() 用于删除文件或文件夹
boolean createNewFile() - 用于创建新的空文件。
File[] listFiles() - 用于获取目录中的所有内容。
boolean isFile() - 用于判断是否为一个文件。
boolean isDirectory() - 用于判断是否为一个目录。
boolean mkdir() - 创建目录

File类代码演示:

public class FileTest {
     

	public static void main(String[] args) {
     
		File file = new File("C://User//Desktop//a.txt");
		System.out.println("file类指向的路径是否存在:" + file.exists());
		//exists:判断file类指向的文件路径是否存在,若存在返回true,不存在返回false
		//目的是为了防止文件未找到,若没有该文件,则创建
		if (!file.exists()) {
     
			try {
     
				file.createNewFile();
			} catch (IOException e) {
     
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("文件名称:" + file.getName());
		System.out.println("文件大小(字节个数):" + file.length());
		Date date = new Date(file.lastModified());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		System.out.println("文件最后一次修改的时间:" + sdf.format(date));
		
		file = new File("C://User//Desktop//dir1");
		//创建单个文件夹
		boolean is = file.mkdir();
		System.out.println("创建文件夹:" + is);
		file = new File("C://Users//Desktop//dir1//dir2");
		//创建多个文件夹
		is = file.mkdirs();
		System.out.println("创建文件夹:" + is);
		File[] files = file.listFiles();
		for (File file2 : files) {
     
			String fileType = file2.isFile() ? "文件" : "文件夹";
			System.out.println(fileType + ":" + file2.getName());
		}
		
		//删除dir2
		File f2 = new File("C://User//Desktop//dir1//dir2//dir3");
		//使用delete方法删除,只能删除空文件夹,所以说,先清空dir2中的文件夹,再删除dir2
		f2.delete();
		File f3 = new File("C://User//Desktop//dir1//dir2");
		System.out.println("dir2文件删除:" + f3.delete());
		
	}
}

IO流

简介:I:in,输入流,o:out,输出流,io流分为2大类,字节与字符,以下介绍字节与字符。
IO流体系:
Java基础 -- 呕心沥血的JavaIO流篇笔记_第1张图片

IO流之字节流

什么是字节?
计算机中最小的容量单位
所谓的字节流,就是一个字节一个字节的传输,通常用于图片、视频、音频等文件的读写
FileInputStream

java.io.FileInputStream类,用于对图片、视频、音频等文件的读取操作
常用方法:

FileInputStream(String name) - 根据参数指定的路径名来构造对象与之关联。
int read() - 用于从输入流中读取一个字节的数据并返回,若读取到文件尾则返回-1
int read(byte[] b) - 用于从输入流中读满整个参数指定的数组。
- 若读取到文件尾则返回-1,否则返回实际读取到的字节数。
int read(byte[] b, int off, int len) - 读取len个字节到数组b中。
int available() - 用于获取关联文件的大小并返回。
void close() - 关闭输入流并释放资源。

代码演示:
一次性读取指定字节个数,然后再将读取的字节写入到数组中
int read(byte[] b, int off, int len)
参数1:将读取的字节保存的一个数组
参数2:向数组中写入字节时的偏移量(跳过的元素个数)
参数3:从输入流中读取的长度(字节个数)

public class FileTest {
     

	public static void main(String[] args) {
     
		try {
     
			FileInputStream fis = new FileInputStream("C://Users//Desktop//a.txt");
			//获取文件大小
			int len = fis.available();
			byte[] b = new byte[len];
			int realLen = fis.read(b, 0, b.length);
			byte[] newArr = Arrays.copyOf(b, realLen);
			String str = new String(newArr, "UTF-8");
			System.out.println(str);
		} catch (FileNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

FileOutputStream
java.io.FileOutputStream类,用于对图片、视频、音频文件的写入操作
常用方法

FileOutputStream(String name) - 根据参数指定的路径名来构造对象并关联起来。
FileOutputStream(String name, boolean append) - 以追加的方式构造对象。
void write(int b) - 用于将参数指定的单个字节写入输出流。
void write(byte[] b) - 用于将参数指定的字节数组内容全部写入输出流中。
void write(byte[] b, int off, int len)
void close() - 关闭输出流并释放有关的资源

代码演示:
一次性读取全部内容,再将内容写入指定文件中。

public class FileTest {
     

	public static void main(String[] args) {
     
		try {
     
			FileInputStream fis = new FileInputStream("C://Users//Desktop//a.txt");
			//注:若没有此文件,会在该路径下创建一个文件,所以写入时会创建文件,但读时就不会创建
			FileOutputStream fos = new FileOutputStream("C://Users//Desktop//b.txt");
			//获取文件大小
			int len = fis.available();
			byte[] b = new byte[len];
			int realLen = fis.read(b, 0, b.length);
			fos.write(b, 0, realLen);
			System.out.println("写入成功~");
		} catch (FileNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

ObjectOutputStream
java.io.ObjectOutputStream类用于将对象写入到文件中,
前提是:只支持将实现了java.io.Serializable 接口的对象写入到文件中
一个类通过实现java.io.Serializable接口来启用其序列化功能,所谓的序列化就是将一个对象转换成字节码的过程
代码演示
将对象写入文件中

public class FileTest {
     

	public static void main(String[] args) {
     
		Person p1 = new Person("张三", 23);
		try {
     
			OutputStream os = new FileOutputStream("C://Users//Desktop//c.txt");
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(p1);
			System.out.println("");
		} catch (FileNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

class Person implements Serializable{
     
	private String name;
	private int age;
	
	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;
	}
}

ObjectInputStream
java.io.ObjectInputStream类,用于从一个文件中读取对象的信息

代码演示
定义Person类,序列化,实例化三个对象放入集合中,将集合写入文件内,再从文件内读出输出在控制台

public class FileTest {
     

	public static void main(String[] args) {
     
		ArrayList<Person> persons = new ArrayList<Person>();
		persons.add(new Person("张三", 23));
		persons.add(new Person("李四", 24));
		persons.add(new Person("王五", 26));
		
		try {
     
			OutputStream os = new FileOutputStream("C://Users//Desktop//d.txt");
			ObjectOutputStream oos = new ObjectOutputStream(os);
			//将对象集合写入文件内
			oos.writeObject(persons);
			
			InputStream is = new FileInputStream("C://Users//Desktop//d.txt");
			ObjectInputStream ois = new ObjectInputStream(is);
			//将集合对象从文件中读出
			ArrayList<Person> persons2 = (ArrayList<Person>) ois.readObject();
			//利用stream流遍历集合中内容
			persons2.stream().forEach(s	->{
     
				System.out.println(s.toString());
			});
		} catch (FileNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

class Person implements Serializable{
     
	private String name;
	private int age;
	
	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 + "]";
	}
	
}

IO流之字符流

字符流,就是一个字符一个字符的传输,不管中文,还是英文,通常用于文本文件的读写。

FileWriter
java.io.FileWriter类,用于向文本文件中写入字符数据
代码演示:
利用字符流FileWriter向文件中写入数据

public class FileTest {
     

	public static void main(String[] args) {
     
		try {
     
			FileWriter fw = new FileWriter("C://Users//Desktop//c.txt");
			fw.write("Hello China");
			System.out.println("写入成功~");
			//必须关闭流,否则会写不进去
			fw.close();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

FileReader
java.io.FileReader类,用于从文本文件中读取字符数据

代码演示:
从一个文件中读出内容,再输出读出的内容

public static void main(String[] args) {
     
		try {
     
			FileWriter fw = new FileWriter("C://Users//Desktop//c.txt");
			fw.write("Hello China");
			System.out.println("写入成功~");
			fw.close();
			FileReader fr = new FileReader("C://Users//Desktop//c.txt");
			while (true) {
     
				//一次读取一个字节,无法读取中文
				int i = fr.read();
				if (i == -1) {
     
					break;
				}
				System.out.print((char)i);
			}
			//必须关闭流,否则会写不进去
			fr.close();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

优化代码,可读取中文

public class FileTest {
     

	public static void main(String[] args) {
     
		try {
     
			FileWriter fw = new FileWriter("C://Users//Desktop//c.txt");
			fw.write("Hello China,你好");
			System.out.println("写入成功~");
			fw.close();
			FileReader fr = new FileReader("C://Users//Desktop//c.txt");
			FileInputStream fis = new FileInputStream("C://Users//Desktop//c.txt");
			int len = fis.available();
			char[] cbuf = new char[len];
			int realLen = fr.read(cbuf);
			char[] cbuf2 = Arrays.copyOf(cbuf, realLen);
			System.out.println(Arrays.toString(cbuf2));
			//必须关闭流,否则会写不进去
			fr.close();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

BufferedReader
缓冲读入流,把读出的数据先放入缓冲区内再写入文件中,这样可提升程序的速度

public class FileTest {
     

	public static void main(String[] args) {
     
		try {
     
			Reader in = new FileReader("C://Users//Desktop//c.txt");
			BufferedReader br = new BufferedReader(in);
			String res = "";
			//一次读一行
			while ((res = br.readLine()) != null) {
     
				System.out.println(res);
			}
			in.close();
			br.close();
		} catch (FileNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

BufferedWriter
缓冲写入流,写入完毕需flash手动刷新清空缓冲区内容
代码演示
将内容写入文件中,再读出文件内容

public class FileTest {
     

	public static void main(String[] args) {
     
		Writer writer = null;
		Reader reader = null;
		BufferedWriter bw = null;
		BufferedReader br = null;
		try {
     
			writer = new FileWriter("C://Users//Desktop//c.txt");
			reader = new FileReader("C://Users//Desktop//c.txt");
			bw = new BufferedWriter(writer);
			br = new BufferedReader(reader);
			bw.write("你好21345612324");
			bw.close();
			String str = "";
			while ((str = br.readLine()) != null) {
     
				System.out.println(str);
			}
			reader.close();
			br.close();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Properties集合
Properties类,表示一个属性集合,用来对键值对数据(key=value)进行读写操作

常用方法

setProperty(String key,String value),向集合中添加数据
store,把集合中的数据持久化到文件中
load,把文件中的数据读取到内存中
getProperty(String key),从集合中根据key获取值

向文件中写入键值对数据,从文件中读出键值对数据
代码演示

public class FileTest {
     

	public static void main(String[] args) {
     
		Properties pro = new Properties();
		try {
     
			File file = new File("C://Users//Desktop//conf.properties");
			if (!file.exists()) {
     
				file.createNewFile();
			}
			FileReader fr = new FileReader("C://Users//Desktop//conf.properties");
			pro.load(fr);
			if (fr != null) {
     
				fr.close();
			}
			FileWriter fw = new FileWriter("C://Users//王会称//Desktop//conf.properties");
			pro.setProperty("name", "张三");
			pro.setProperty("sex", "男");
			pro.store(fw, "store success");
			if (fw != null) {
     
				fw.close();
			}
			System.out.println(pro);
		} catch (FileNotFoundException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

练习:
使用Properties类,创建一个属性文件db.properties,有如下内容:
host=localhost
user=root
pass=root
port=3306
然后再使用Properties类读取该属性文件,并输出

public class FileTest {
     

	public static void main(String[] args) {
     
		Properties pro = new Properties();
		try {
     
			FileWriter fw = new FileWriter("C://Users//Desktop//db.properties");
			pro.setProperty("host", "localhost");
			pro.setProperty("user", "root");
			pro.setProperty("pass", "111111");
			pro.setProperty("port", "3306");
			pro.store(fw, "store success");
			if (fw != null) {
     
				fw.close();
			}
			FileReader fr = new FileReader("C://Users//Desktop//db.properties");
			pro.load(fr);
			fr.close();
			System.out.println(pro);
		} catch (IOException e) {
     
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

IO流篇到此结束了,看到这的小伙伴来个三连支持下作者吧,

你可能感兴趣的:(Java学习笔记,java,大数据)