Java学习IO流(三)

Properties类

properties类表示了一个持久的属性集,Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

特点:

1Hashtable的子类,map集合中的方法都可以用。

2、该集合没有泛型。键值都是字符串

3、它是一个可以持久化的属性集。键值可以存储到集合中,也可以存储到持久化的设备(硬盘、U盘、光盘)上。键值的来源也可以是持久化的设备。

4、有和流技术相结合的方法。

 load(InputStream)  把指定流所对应的文件中的数据,读取出来,保存到Propertie集合中

 load(Reader)  

 store(OutputStream,commonts)把集合中的数据,保存到指定的流所对应的文件中,参数commonts代表对描述信息

 stroe(Writer,comments);

package com.oracle.demo01;

import java.util.Properties;
import java.util.Set;

public class PropertiesDemo {
	public static void main(String[] args) {
		Properties pro = new Properties();
		// Properties集合 添加元素,都是String类型的 相当于map集合中的put方法
		pro.setProperty("a", "1");
		pro.setProperty("b", "2");
		pro.setProperty("c", "3");
		pro.setProperty("d", "4");
		pro.setProperty("e", "5");

		// 循环遍历 获取到装有键集的set集合   相当于遍历map集合的keySet()方法
		Set<String> s = pro.stringPropertyNames();
		for (String str : s) {
			// 通过遍历键获取对应的值
			String key = str;
			String value = pro.getProperty(key);
			System.out.println(key + "---" + value);
		}
	}
}

将集合中的内容存储到文件中

package com.oracle.demo01;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class PropertiesDemo01 {
	public static void main(String[] args) throws IOException {
		input();
	}

	public static void output() throws IOException {
		// 创建Properties集合
		Properties pro = new Properties();
		// 添加元素到集合
		pro.setProperty("张三", "1");
		pro.setProperty("李四", "2");
		pro.setProperty("王五", "3");
		pro.setProperty("赵六", "4");
		// 创建流对象
		//用字节流完成非中文的读取操作
		//FileOutputStream fos = new FileOutputStream("e:\\test\\demo.properties");
		//用字符流完成中文的读取操作
        FileWriter fw=new FileWriter("e:\\test\\demo.properties");
		// 将集合中的数据存入流所对应的文件中
		pro.store(fw, "张三");
		// 关闭流
		fw.close();
	}
	public static void input() throws IOException{
		//创建集合
		Properties pro = new Properties();
        //创建流对象
		FileReader fr=new FileReader("e:\\test\\demo.properties");
		//读取流所对应的文件中的数据到集合中
		pro.load(fr);
		//关闭流
		fr.close();
		Set<String> set =pro.stringPropertyNames();
		Iterator<String> it=set.iterator();
		while(it.hasNext()){
			String key=it.next();
			String value=pro.getProperty(key);
			System.out.println(key+"---"+value);
		}
	}
}

系列化与反序列化

用于向流中写入对象的操作流 ObjectOutputStream   称为 序列化流

用于从流中读取对象的操作流 ObjectInputStream    称为 反序列化流

特点:用于操作对象。可以将对象写入到文件中,也可以从文件中读取对象。

 

 

对象的序列化ObjectOutputStream

构造方法:

常用方法:

对象的反序列化ObjectInputStream

构造方法:

常用方法:

注:

当一个对象要能被序列化,这个对象所属的类必须实现Serializable接口。否则会发生异常NotSerializableException异常。

同时当反序列化对象时,如果对象所属的class文件在序列化之后进行了修改,那么进行反序列化也会发生异常InvalidClassException。发生这个异常的原因如下:

1、 该类的序列版本号与从流中读取的类描述符的版本号不匹配

2、 该类包含未知数据类型

3、 该类没有可访问的无参数构造方法

Serializable标记接口。该接口给需要序列化的类,提供了一个序列版本号。serialVersionUID. 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。

瞬态关键字transient

当一个类的对象需要被序列化时,某些属性不需要被序列化,这时不需要序列化的属性可以使用关键字transient修饰。只要被transient修饰了,序列化时这个属性就不会琲序列化了。

同时静态修饰的成员变量也不会被序列化,因为序列化是把对象数据进行持久化存储,而静态的属于类加载时的数据,不会被序列化。

package com.oracle.demo03;

import java.io.Serializable;

//序列化需要实现Serializable接口以启用序列化功能
//Serializable接口含义:标记型接口(什么也没有的接口)
//作用:对Person类做一个标记,只有这个标记就可以序列化
public class Person implements Serializable {
	private String name;
	// 当类中的成员变量被static修饰时,就成为了静态成员变量
	// 此时静态成员变量不能被序列化与反序列化。因为静态不属于对象,只属于自己的类,并有默认值
	// private static int age;
	//private int age;
	public int age;
	// 假如不想成员变量序列化,也不想变化静态的
	// 此时就用transient关键字去解决 瞬态关键字
	
	private transient String sex;
	//序列号写死
	static final long serialVersionUID = 42L;

	public Person() {
	}

	public Person(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	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;
	}

}
package com.oracle.demo03;

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

public class Test {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		//当修改完Person类中的内容时,就要先序列化,再反序列化
		//output();
		input();
	}

	// 序列化
	public static void output() throws IOException {
		FileOutputStream fos = new FileOutputStream("e:\\test\\Person.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		Person p = new Person("张三", 18,"男");
		oos.writeObject(p);
		oos.close();
	}

	// 反序列化
	public static void input() throws ClassNotFoundException, IOException {
		FileInputStream fis = new FileInputStream("e:\\test\\Person.txt");
		ObjectInputStream ois = new ObjectInputStream(fis);
		Person p = (Person)ois.readObject();
		ois.close();
		System.out.println(p);
	}
}

打印流

打印流添加输出数据的功能,使它们能够方便地打印各种数据值表示形式.

打印流根据流的分类:

1、 字节打印流 PrintStream

2、 字符打印流 PrintWriter

常用方法:

void print(String str): 输出任意类型的数据,

void println(String str): 输出任意类型的数据,自动写入换行操作

打印流完成数据自动刷新

可以通过构造方法,完成文件数据的自动刷新功能

l 构造方法:

l 开启文件自动刷新写入功能

public PrintWriter(OutputStream out, boolean autoFlush)

public PrintWriter(Writer out, boolean autoFlush)

package com.oracle.demo03;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintDemo {
	/*
	 * 打印流
	 * 1、PrintStream
	 *    构造方法:可以传入 File、Output、String、Writer
	 * 2、PrintWriter(自动刷新功能)
	 *    构造方法:可以传入 File、Output、String
	 *    二者方法一样
	 * 特点:
	 * 1、该流不负责数据源,只负责数据目的
	 * 2、为其他输出流添加功能
	 * 3、永远不抛IOException
	 * */
     public static void main(String[] args) throws IOException {
		//method();
		//method3();
    	 copy();
	}
     public static void method() throws IOException{
    	 File file=new File("e:\\test\\number.txt");
    	 PrintWriter pw=new PrintWriter(file);
    	 pw.println(100);
    	 pw.write(100);
    	 pw.close();
     }
     //输出语句如果是char[]数组得问题
     public static void method2(){
    	 int[] arr={1};
    	 System.out.println(arr);
    	 char[] ch={'a','b'};
    	 System.out.println(ch);
     }
     //打印流得自动刷新功能
     //条件:1、你的输出数据目的必须是一个流对象
     //      2、必须调用的方法是println、printf、format
     public static void method3() throws IOException{
    	 File file=new File("e:\\test\\number.txt");
         FileOutputStream fos=new FileOutputStream(file);
    	 PrintWriter pw=new PrintWriter(fos,true);
         pw.println("12133");
         pw.println("asdaf");
         pw.println("akni12231");
         pw.close();
     }
     //复制文件
     public static void copy() throws IOException{
    	 //读取数据:BufferedReader+FileReader
    	 //写入目的地:PrintWriter+println  自动刷新功能
    	 BufferedReader br=new BufferedReader(new FileReader("e:\\test\\number.txt"));
    	 PrintWriter pw=new PrintWriter(new FileWriter("e:test\\a\\wenjian.txt"),true);
    	 String line=null;
    	 while((line=br.readLine())!=null){
    		 pw.println(line);
    	 }
    	 pw.close();
    	 br.close();
     }
}

commons-IO

导入classpath

加入classpath的第三方jar包内的class文件才能在项目中使用

创建lib文件夹

commons-io.jar拷贝到lib文件夹

右键点击commons-io.jarBuild PathAdd to Build Path

FilenameUtils

这个工具类是用来处理文件名(译者注:包含文件路径)的,他可以轻松解决不同操作系统文件名称规范不同的问题

l 常用方法:

getExtension(String path):获取文件的扩展名;

getName():获取文件名;

isExtension(String fileName,String ext):判断fileName是否是ext后缀名;

FileUtils

提供文件操作(移动文件,读取文件,检查文件是否存在等等)的方法。

l 常用方法:

readFileToString(File file):读取文件内容,并返回一个String;

writeStringToFile(File file,String content):将内容content写入到file中;

copyDirectoryToDirectory(File srcDir,File destDir);文件夹复制

copyFile(File srcFile,File destFile);文件夹复制

package com.oracle.demo04;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsDemo {
	public static void main(String[] args) throws IOException {
		FileNameUtilsMethod();
	}

	public static void FileNameUtilsMethod() throws IOException {
		FilenameUtils fnu = new FilenameUtils();
		// 获取后缀名
		String str = fnu.getExtension("e:\\test\\number.txt");
		// 获取文件名
		String str2 = fnu.getName("e:\\test\\number.txt");
		// 判断后缀名
		boolean b = fnu.isExtension("e:\\test\\number.txt", "txt");
		System.out.println(b);
		//读取文件内容
		FileUtils fu=new FileUtils();
		String content=fu.readFileToString(new File("e:\\test\\number.txt"));
		System.out.println(content);
		//将字符串写入文件
		fu.writeStringToFile(new File("e:\\test\\number.txt"), "今天下雨了");
		//文件夹的复制
		fu.copyDirectoryToDirectory(new File("e:\\test"), new File("e:\\test2"));
		
	}
	
}

  

猜你喜欢

转载自www.cnblogs.com/Java-125/p/8921587.html