1.FIle对象

1.1 遍历文件或目录

**
 * 列出C盘的目录和文件
 * @author lenovo
 *
 */
public class FIleListDemo1 {

	public static void main(String[] args) {
		
//		FIleListDemo1();
		
//		FIleListDemo2();
		
		FIleListDemo3();
		
	}

	//找出C盘下的所有隐藏文件
	public static void FIleListDemo3() {
		
		File file=new File("C:\\");
		File[] listFiles = file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				
				return !pathname.isHidden();
			}
		});
		for (File f : listFiles) {
			System.out.println(f.getName());
		}
		
	}

	//找出磁盘下的.txt文件(使用了文件名过滤器)
	public static void FIleListDemo2() {

		File file=new File("C:\\");
		String[] list = file.list(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".txt");
			}
		});
		for (String f : list) {
			System.out.println(f);
		}
	
	}

//	列出C盘的目录和文件
	public static void FIleListDemo1() {
		
		File file=new File("C:\\");
		String[] list = file.list();
		for (String f : list) {
			System.out.println(f);
		}
	}
}

1.2 文件深度遍历

java读取e盘图片 java读取c盘文件_输出流

1.3目录深度删除

java读取e盘图片 java读取c盘文件_配置文件_02

2. Properties

2.1基本api

public class PropertiesDemo {

	public static void main(String[] args) throws IOException {

		/*
		 * Map
		 * 	|--Hashtable
		 * 		|--Properties:
		 * 
		 * Properties集合:
		 * 特点:
		 * 1,该集合中的键和值都是字符串类型。
		 * 2,集合中的数据可以保存到流中,或者从流获取。
		 * 
		 * 通常该集合用于操作以键值对形式存在的配置文件。 
		 */
		
//		methodDemo_4();
//		myLoad();
		
		test();
	}
	
	//对已有的配置文件中的信息进行修改。 
	/*
	 * 读取这个文件。
	 * 并将这个文件中的键值数据存储到集合中。
	 * 在通过集合对数据进行修改。
	 * 在通过流将修改后的数据存储到文件中。 
	 */
	public static void test() throws IOException{
		//读取这个文件。
		File file = new File("info.txt");
		if(!file.exists()){
			file.createNewFile();
		}
		FileReader fr = new FileReader(file);
			
		//创建集合存储配置信息。
		Properties prop = new Properties();
		
		//将流中信息存储到集合中。
		prop.load(fr);
		
		prop.setProperty("wangwu", "16");
			
		FileWriter fw = new FileWriter(file);
		
		prop.store(fw,"");
		
//		prop.list(System.out);
		
		fw.close();
		fr.close();
			
	}
	
	//模拟一下load方法。
	public static void myLoad() throws IOException{
		
		Properties prop  = new Properties();
		
		BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));
		
		String line = null;
		
		while((line=bufr.readLine())!=null){
			
			if(line.startsWith("#"))
				continue;
			
			String[] arr = line.split("=");
			
//			System.out.println(arr[0]+"::"+arr[1]);
			prop.setProperty(arr[0], arr[1]);
		}
		
		prop.list(System.out);
		
		bufr.close();
		
	}
	
	public static void methodDemo_4() throws IOException {	
		
		Properties prop  = new Properties();
		
		//集合中的数据来自于一个文件。 
		//注意;必须要保证该文件中的数据是键值对。
		//需要使用到读取流。 
		FileInputStream fis = new FileInputStream("info.txt");
		
		//使用load方法。 
		prop.load(fis);
		
		prop.list(System.out);
			
	}

	public static void methodDemo_3() throws IOException {
		Properties prop  = new Properties();
		
		//存储元素。 
		prop.setProperty("zhangsan","30");
		prop.setProperty("lisi","31");
		prop.setProperty("wangwu","36");
		prop.setProperty("zhaoliu","20");
		
		//想要将这些集合中的字符串键值信息持久化存储到文件中。
		//需要关联输出流。
		FileOutputStream fos = new FileOutputStream("info.txt");
		
		//将集合中数据存储到文件中,使用store方法。
		prop.store(fos, "info");
		
		fos.close();
		
	}

	/**
	 * 演示Properties集合和流对象相结合的功能。
	 */
	
	public static void methodDemo_2(){
		Properties prop  = new Properties();
		
		//存储元素。 
//		prop.setProperty("zhangsan","30");
//		prop.setProperty("lisi","31");
//		prop.setProperty("wangwu","36");
//		prop.setProperty("zhaoliu","20");
	
		prop = System.getProperties();
		prop.list(System.out);
	}
	
	/*
	 * Properties集合的存和取。
	 */
	
	public static void propertiesDemo(){
		//创建一个Properties集合。
		
		Properties prop  = new Properties();
		
		//存储元素。 
		prop.setProperty("zhangsan","30");
		prop.setProperty("lisi","31");
		prop.setProperty("wangwu","36");
		prop.setProperty("zhaoliu","20");
		
		//修改元素。 
		prop.setProperty("wangwu","26");
		
		//取出所有元素。
		Set<String> names = prop.stringPropertyNames();
		
		for(String name : names){
			String value = prop.getProperty(name);
			System.out.println(name+":"+value);
		}
	}
}

2.2 小栗子

使用计数器记录程序运行的次数,达到5次后,禁止程序运行

public class PropertiesTest {

	public static void main(String[] args) throws IOException {
		grtPrommerCount();
	}

	public static void grtPrommerCount() throws IOException {
		
		File file=new File("config.properties");
		
		if (!file.exists()) {
			file.createNewFile();
		}
		FileInputStream fis=new FileInputStream(file);
		Properties pros=new Properties();
		pros.load(fis);
		String pcount = pros.getProperty("count");
		int count=0;
		if (pcount!=null) {
			count=Integer.parseInt(pcount);
		}
		count++;
		if (count>5) {
			throw new RuntimeException("交钱!!!");
		}
		pros.setProperty("count", count+"");
		FileOutputStream fos=new FileOutputStream(file);
		pros.store(fos,"count=time");
	}
}

3. 打印流(保持数据的原本格式)

3.1 PrintStream

public class PrintStreamDemo {

	public static void main(String[] args) throws IOException {

		/*
		 * PrintStream:
		 * 1,提供了打印方法可以对多种数据类型值进行打印。并保持数据的表示形式。 
		 * 2,它不抛IOException.
		 * 
		 * 构造函数,接收三种类型的值:
		 * 1,字符串路径。
		 * 2,File对象。
		 * 3,字节输出流。
		 */
		
		PrintStream out = new PrintStream("print.txt");
		
//		int by = read();
//		write(by);
		
//		out.write(610);//只写最低8位,
		
//		out.print(97);//将97先变成字符保持原样将数据打印到目的地。 
		
		out.close();

	}
}

3.2 PrintWriter

public class PrintWriterDemo {

	public static void main(String[] args) throws IOException {
		/*
		 * PrintWriter:字符打印流。
		 * 构造函数参数:
		 * 1,字符串路径。
		 * 2,File对象。
		 * 3,字节输出流。
		 * 4,字符输出流。
		 * 
		 */
		BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
		
		PrintWriter out = new PrintWriter(new FileWriter("out.txt"),true);
		
		String line =  null;
		while((line=bufr.readLine())!=null){
			if("over".equals(line))
				break;
			out.println(line.toUpperCase());
//			out.flush();
		}	
		out.close();
		bufr.close();
	}
}

4. 序列流----SequenceInputStream

将几个输入流整合成一个输入流

例子:将三个文件的内容读取到另外一个文件里

public class SequenceInputStreamDemo {

	public static void main(String[] args) throws IOException {
		
		ArrayList<FileInputStream>list=new ArrayList<FileInputStream>();
		for (int i = 1; i <= 3; i++) {
			list.add(new FileInputStream(i+".txt"));
		}
		Enumeration<FileInputStream> e = Collections.enumeration(list);
		SequenceInputStream sis=new SequenceInputStream(e);
		FileOutputStream fos=new FileOutputStream("4.txt");
		byte[] buf=new byte[1024];
		int len=0;
		while((len=sis.read(buf))!=-1) {
			fos.write(buf, 0, len);
			fos.flush();
		}
		fos.close();
		sis.close();
	}
}

5.文件切割和复原

5.1 普通版本的文件切割(不带配置文件信息的)

5.1.1 文件切割

public static void fileSplite(File file) throws IOException {
		// 输入流
		FileInputStream fis = new FileInputStream(file);
		// 构建缓冲区
		byte[] buf = new byte[SIZE];
		int len = 0;
		// 目的
		File fout = new File("E:\\partFiles");
		if (!fout.exists()) {
			fout.mkdirs();
		}
		// 定义输出流
		FileOutputStream fos = null;
		// 定义计数器
		int count = 0;
		while ((len = fis.read(buf)) != -1) {
			fos = new FileOutputStream(new File(fout, (count++) + ".part"));
			fos.write(buf, 0, len);
			fos.flush();
		}
		fis.close();
		fos.close();
	}

5.1.2 文件复原

public static void mergefile(File file) throws IOException {
		// 缓冲区
		ArrayList<FileInputStream> arrayList = new ArrayList<FileInputStream>();
		// 读
		for (int i = 0; i <= 23; i++) {
			arrayList.add(new FileInputStream(new File(file, i + ".part")));
		}
		// 生成枚举
		Enumeration<FileInputStream> e = Collections.enumeration(arrayList);
		// 序列流
		SequenceInputStream sis = new SequenceInputStream(e);
		// 目的
		FileOutputStream fos = new FileOutputStream("E:\\1.bmp");
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = sis.read(buf)) != -1) {
			fos.write(buf, 0, len);
			fos.flush();
		}
		fos.close();
		sis.close();
	}

5.2 带配置文件文件切割和复原

  • 文件名过滤器 
public class FileFilterByName implements FilenameFilter {

	private String suf;
	public FileFilterByName(String suf) {
		super();
		this.suf = suf;
	}
	@Override
	public boolean accept(File dir, String name) {
		return name.endsWith(suf);
	}
}
  • 配置文件 

java读取e盘图片 java读取c盘文件_配置文件_03

 5.2.1 文件切割

public class FIleSpliteTest {

	private static final int SIZE = 1024 * 1024;

	public static void main(String[] args) throws IOException {

		File file = new File("E:\\0.bmp");
		fileSplite_2(file);
	}

	/**
	 * 带配置文件的
	 * @param file
	 * @throws IOException
	 */
	public static void fileSplite_2(File file) throws IOException {

		// 输入流
		FileInputStream fis = new FileInputStream(file);
		// 构建缓冲区
		byte[] buf = new byte[SIZE];
		int len = 0;
		// 目的
		File fout = new File("E:\\partFiles");
		if (!fout.exists()) {
			fout.mkdirs();
		}
		// 定义输出流
		FileOutputStream fos = null;
		// 定义计数器
		int count = 1;
		while ((len = fis.read(buf)) != -1) {
			fos = new FileOutputStream(new File(fout, (count++) + ".part"));
			fos.write(buf, 0, len);
			fos.close();;
		}
		
		//存储 文件名 和 碎片文件个数
		Properties properties=new Properties();
		properties.setProperty("partCount", count+"");
		properties.setProperty("fileName", file.getName());
		
		//配置文件输出流
		fos=new FileOutputStream(new File(fout, count+".properties"));
		properties.store(fos, "partInof");
		fis.close();
		fos.close();

	}

}

5.2.2 文件复原 

public class FIleMergeTest {

	public static void main(String[] args) throws IOException {

		File dir = new File("E:\\partFiles");
		mergefile_2(dir);
	}

	// 不带配置文件的
	public static void mergefile_2(File dir) throws IOException {

		// 从指定目录中找出配置文件=====================
		File[] listFiles = dir.listFiles(new FileFilterByName(".properties"));
		if (listFiles.length != 1) {
			throw new RuntimeException("配置文件不存在或者数目不唯一!!!");
		}
		
		// 加载配置文件
		FileInputStream confis = new FileInputStream(listFiles[0]);
		Properties pts = new Properties();
		pts.load(confis);

		// 从配置文件中读出文件名和碎片文件个数
		int count = Integer.parseInt(pts.getProperty("partCount"));
		String fileName = pts.getProperty("fileName");

		
		// 存储输入流的容器================
		ArrayList<FileInputStream> arrayList = new ArrayList<FileInputStream>();
		//获取该目录下的所有碎片文件
		File[] parts = dir.listFiles(new FileFilterByName(".part"));
		if (parts.length!=count-1) {
			throw new RuntimeException("碎片文件个数不对!!!");
		}
		// 读
		for (int i = 0; i < parts.length; i++) {
			arrayList.add(new FileInputStream(parts[i]));
		}
		// 生成枚举
		Enumeration<FileInputStream> e = Collections.enumeration(arrayList);
		// 序列流
		SequenceInputStream sis = new SequenceInputStream(e);
		// 目的
		FileOutputStream fos = new FileOutputStream(new File(dir,fileName));
		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = sis.read(buf)) != -1) {
			fos.write(buf, 0, len);
			fos.flush();
		}
		fos.close();
		sis.close();
	}	
}

6. 序列化和反序列化(Seriable)

6.1 bean类

/**
 * 将要被序列化和反序列化的类
 * @author lenovo
 *	实现Seriable接口为了使该类和对象和版本号一致
 */
public class Persion implements Serializable{

	private static final long serialVersionUID = 1L;

	private String name;
	private int age;
	public Persion(String name, int age) {
		super();
		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;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	@Override
	public String toString() {
		return "Persion [name=" + name + ", age=" + age + "]";
	}
}

6.2 序列化和反序列化演示

/**
 * 序列化和反序列化演示
 */
public class ObjectStreamDemo {
	
	public static void main(String[] args) throws Exception {
//		objectStream_1();
		objectStream_2();
		
	}

	public static void objectStream_2() throws Exception {
		
		ObjectInputStream obj=new ObjectInputStream(new FileInputStream("demo1.object"));
		Persion persion=(Persion)obj.readObject();
		System.out.println(persion);
	}

	//对象的序列化
	public static void objectStream_1() throws IOException {
		
		ObjectOutputStream obj=new ObjectOutputStream(new FileOutputStream("demo1.object"));
		obj.writeObject(new Persion("王五", 10));
		obj.close();
	}
}

6.3 非静态数据不想被序列化可以使用(transient)关键字修饰

java读取e盘图片 java读取c盘文件_java读取e盘图片_04

7. RandomAccessFile

public class RandomAccessFileDemo {

	public static void main(String[] args) throws IOException {

		/*
		 * RandomAccessFile
		 * 一看这个类名字,纠结。不是io体系中的子类。
		 * 
		 * 特点:
		 * 1,该对象即能读,又能写。
		 * 2,该对象内部维护了一个byte数组,并通过指针可以操作数组中的元素,
		 * 3,可以通过getFilePointer方法获取指针的位置,和通过seek方法设置指针的位置。
		 * 4,其实该对象就是将字节输入流和输出流进行了封装。 
		 * 5,该对象的源或者目的只能是文件。通过构造函数就可以看出。  
		 */
		
//		writeFile();
//		readFile();
		randomWrite();
	}
	
	public static void randomWrite() throws IOException{
		RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "rw");
		
		//往指定位置写入数据。
		raf.seek(3*8);
		
		raf.write("哈哈".getBytes());
		raf.writeInt(108);
		
		raf.close();
	}
		
	public static void readFile() throws IOException {
		
		RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "r");
		
		//通过seek设置指针的位置。
		raf.seek(1*8);//随机的读取。只要指定指针的位置即可。 
		
		byte[] buf = new byte[4];
		raf.read(buf);
		
		String name = new String(buf);
		
		int age = raf.readInt();
		
		System.out.println("name="+name);
		System.out.println("age="+age);
		
		System.out.println("pos:"+raf.getFilePointer());
		
		raf.close();			
	}

	//使用RandomAccessFile对象写入一些人员信息,比如姓名和年龄。
	public static void writeFile() throws IOException{
		/*
		 * 如果文件不存在,则创建,如果文件存在,不创建
		 * 
		 */
		RandomAccessFile raf = new RandomAccessFile("ranacc.txt","rw");
		
		raf.write("张三".getBytes());
		raf.writeInt(97);
		raf.write("小强".getBytes());
		raf.writeInt(99);	
		raf.close();
	}
}

8. 管道流

public class PipedStream {

	public static void main(String[] args) throws IOException {

		PipedInputStream input = new PipedInputStream();
		PipedOutputStream output = new PipedOutputStream();
		
		input.connect(output);		
		new Thread(new Input(input)).start();
		new Thread(new Output(output)).start();		
	}
}


class Input implements Runnable{
	
	private PipedInputStream in;
	Input(PipedInputStream in){
		this.in = in;
	}
	public void run(){
		
		try {
			byte[] buf = new byte[1024];
			int len = in.read(buf);
			
			String s = new String(buf,0,len);
			
			System.out.println("s="+s);
			in.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

class Output implements Runnable{
	private PipedOutputStream out;
	Output(PipedOutputStream out){
		this.out = out;
	}
	public void run(){
		
		try {
			Thread.sleep(5000);
			out.write("hi,管道来了!".getBytes());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

9. 操作基本数据类型的流(DataInputStream和DataOutputStream)

public class DataSteamDemo {

	public static void main(String[] args) throws IOException {
		
//		writeData();
		readData();	
	}
	
	public static void readData() throws IOException {
		
		DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));	
		String str = dis.readUTF();	
		System.out.println(str);
	}

	public static void writeData() throws IOException {
		
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));		
		dos.writeUTF("你好");	
		dos.close();	
	}
}

10. 操作内存的流

10.1字符数组的流

ByteArrayInputStream和ByteArrayOutputStream

public class ByteArrayStreamDemo {

	public static void main(String[] args) {

		ByteArrayInputStream bis = new ByteArrayInputStream("abcedf".getBytes());
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		int ch = 0;
		
		while((ch=bis.read())!=-1){
			bos.write(ch);
		}		
		System.out.println(bos.toString());
	}
}

10.2 字符数组流

CharArrayReader   和   CharArrayWriter