Java - 文件和IO流

版权声明:call me 刘英雄 https://blog.csdn.net/weixin_42526141/article/details/82876720

文件:File类

Java就提供了一个File类,以抽象的方式代表文件名和目录路径名。该类主要用于文件和目录的创建、文件的查找和文件的删除等。是我们后面学习IO流的基础和前提

File对象代表磁盘中实际存在的文件和目录,我们可以通过递归算法知道磁盘中某一个目录下嵌套了多少文件。

递归算法(英语:recursion algorithm):程序调用自身的编程技巧称为递归( recursion)。递归做为一种算法在程序设计语言中广泛应用在计算机科学中,指一种通过重复将问题分解为同类的子问题而解决问题的方法。递归式方法可以被用于解决很多的计算机科学问题,因此它是计算机科学中十分重要的一个概念。绝大多数编程语言支持函数的自调用,在这些语言中函数可以通过调用自身来进行递归。计算理论可以证明递归的作用可以完全取代循环,因此在很多函数编程语言(如Scheme)中习惯用递归来实现循环。

递归算法解决问题的特点:

1)递归就是方法里调用自身。

2)在使用递增归策略时,必须有一个明确的递归结束条件,称为递归出口。

3)递归算法解题通常显得很简洁,但递归算法解题的运行效率较低。

package com.liudm.demo13;

import java.io.File;
import java.io.IOException;
import java.net.PasswordAuthentication;

public class FileDemo {
	public static void main(String[] args) throws IOException {
		File file = new File("D:\\bxk");   //两个“\”:第一个“\”是用来转义第二个“\”
		System.out.println(file.exists());   //判断文件是否存在
		System.out.println(file.isFile());   //判断是否是一个文件
		System.out.println(file.isDirectory());  //判断是否是一个文件夹
		System.out.println(file.getAbsolutePath());  //返回file文件的绝对路径
		System.out.println(file.getPath());  //返回相对路径
		
		File [] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			System.out.println(files[i]);  //列举该目录下这一级的所有文件/文件夹
		}

		if (file.createNewFile()) {
			System.out.println("文件创建成功");  //到D盘查看,aa.txt已创建
		}
		
		if (file.mkdir()) {   //只创建自己
			System.out.println("文件夹创建成功");
		}
		
		File file1 = new File("D:\\bxk1\\bkx2\\bxk3");
		if (file1.mkdirs()) {   //创建目录,包括父目录
			System.out.println("子文件夹创建成功");
		}
		
		//delete():只能删除空文件夹,即该文件夹中不能有内容
		file.delete();
		file1.delete();   //只删除了最下层子文件夹
	}
}
package com.liudm.demo13;

import java.io.File;

public class FileDemo1 {
	
	//递归,列举该目录下包括子目录下的所有文件
	public static  void  listFile(File file){
		//File file=new File(pathName);
		if(file.exists()){
			if(file.isDirectory()){
				File  [] files=file.listFiles();
				for (int i = 0; i < files.length; i++) {
					listFile(files[i]);
//					System.out.println(files[i]);
				}
			}else{
				System.out.println(file.getPath());  //打印名字
			}
		}else{
			System.out.println("该目录不存在");
		}
	}
	public static void main(String[] args) {
		
		listFile(new File("D:\\7-Zip"));
		
//		File file = new File("D:\\soft");
//		File  [] files=file.listFiles();
//		for (int i = 0; i < files.length; i++) {
//			System.out.println(files[i]);
//		}
	}
}

 实验:编写代码实现遍历本地目录(自己定义一个存在的目录)下的所有文件,并打印文件的名字在控制台

1. 打开终端切换目录到/data/目录下,创建文件夹file

2.进入file目录,使用wget命令,下载实验需要的数据

3、解压所需要的数据

       unzip data.zip  

package com.liudm.test7;

import java.io.File;

public class FileTest {
	public static void main(String[] args) {
		File file = new File("/data/java3/file");
		FileTest ft = new FileTest();
		ft.GetFileName(file);
	}

	private void GetFileName(File file) {
		// TODO Auto-generated method stub
		if (file.isDirectory()) {
			File [] fs = file.listFiles();
			for (int i = 0; i < fs.length; i++) {
				GetFileName(fs[i]);
			}
		} else {
			System.out.println(file.getName());
		}
	}
}

流:

主要应用场景是上传下载

java中的流是指一连串流动的字符,是以先进先出方式发送信息的通道

流架构:

流分类:

  • 按照流向区分:输入流和输出流(输入输出流是相对于计算机内存来说的)
  • 按照内存单元划分:字节流和字符流

字符流:处理包含大量中文的文本文件

  • 字符输入流:Reader(父)---》FileReader(低级流)-->BufferedReader(高级流)
  • 字符输出流:Writer(父)---》FileWriter(低级流)-->BufferedWriter(高级流)

低级流:也称节点流,节点流类型常见的有:对文件操作的字符流有FileReader/FileWriter,字节流有FileInputStream/FileOutputStream

高级流:也称缓冲流,缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写效率,同时增加了一些新的方法,常用缓冲流有BufferedReader、BufferedWriter

注意:

1.只需要 关闭高级流即可:关高级流,其实就是关低级流,关流的时候,自动刷新缓冲区

                  bw.flush();

2.高级流构造器中传入低级流构,体现了 装饰者 模式,让高级流功能更加强大

                  FileWriter fw = new FileWriter("F:/fw.txt");// 低级流

                  BufferedWriter bw = new BufferedWriter(fw);  //高级流,有缓冲

3.输出流向外写数据的时候,如果目标地址不存在,自动创建

字节流:字节流是 8 位通用字节流,常用来处理图片、视频、文件

字节输入流:InputStream(父)---》

FileInputStream(子):常用方法:read() 、read(byte[])

字节输出流:OutputStream(父)----》

FileOutputStream(子):常用方法:write(int byte) 、 write(byte[])

注意:

1.输出流向外写数据的时候,如果目标地址不存在,自动创建

2.不管是字节输入流还是字节输出流,在读写数据完成之后,一定要手动关闭流资源,一般在finally代码中完成,垃圾回收机制不会自动回收物理资源

3.在用流操作文件的时候,有很多异常需要处理

package com.liudm.demo13;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ByteInDemo {
	public static void main(String[] args) {
		//字节输入流:一个字节一个字节地读,读中文汉字会乱码,一个中文?字节
		//将D:\\FileDemo.java → JVM:内存 → 读进来
		File file = new File("D:\\FileDemo.java");
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			int data = 0;
			
			//读取文件内容:方法一
			while ((data = in.read()) != -1) {   //  ==-1:读到最后一个字符
				//System.out.print(data);  //ASCII码
				System.out.print((char)data);   //强制转换
			}
			
			//读取文件内容:方法二
			byte [] bs = new byte[in.available()];  //bs数组长度为:这个文件内容的大小,用available()获取
			data = in.read(bs);
			System.out.println(new String(bs));
			
			
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			//流:物力资源,一定要手动关闭
			if (in != null) {
				
			}
		}
	}
}
package com.liudm.demo13;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteInDemo1 {
	public static void main(String[] args) throws IOException {
		//字节输出流
		//往外写文件的时候,如果不存在,则创建
		//如果存在不会追加,直接覆盖
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(new File("D:/bxk.txt"));
			out.write(98);
			out.write(97);
			out.write(96);
			System.out.println("写入成功。。");
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}
package com.liudm.demo13;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class CharDemo {
	//字符流,基类:Reader,Writer
	//字节流,基类:InPutStream,OutPutStream
	public static void main(String[] args) {
		//在外面声明,里面赋值
		FileReader fr = null;
		BufferedReader br = null;
		try {
			//模式:装饰者模式
			
			fr = new FileReader(new File ("D:\\FileDemo.java"));  //低级流
			br = new BufferedReader(fr);  //高级流:缓冲区,效率高
			
			String line = null;
			br.readLine();  //一行一行地读
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			
			int data = 0;  //fr.read()
			while ((data = fr.read()) != -1) {
				System.out.println((char)data);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();  //关闭高级流,低级流就不用关闭了
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}
		}
	}
}
package com.liudm.demo13;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CharDemo1 {
	//字符输出流
	public static void main(String[] args) {
		FileWriter fw = null;
		BufferedWriter br = null;
		try {
			fw = new FileWriter(new File("D:\\study.txt"),true);  //在低级流后面加true,表示追加
			br = new BufferedWriter(fw);
			
			char [] c = {'A','B','C','D'};
			br.write("张三");
			br.write(98);
			br.write(c);
			
			br.flush();
			//刷新缓冲区,当没有关流的时候需要读流时,需要刷新缓冲区先读出来
			//读流自动刷新缓冲区
			
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();  //关流的时候会自动刷新缓冲区
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
package com.liudm.demo13;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyDemo {
	public static void main(String[] args) throws IOException {
		CopyDemo.copy("D:\\FileDemo.java","C:\\FileDemo.java");
	}
	
	//图片,视频等,都用字节流
	public static void copy(String start,String end) throws FileNotFoundException{
		FileInputStream in = new FileInputStream(new File(start));
		FileOutputStream out = new FileOutputStream(new File(end));
		
		int data = 0;
		try {
			while ((data = in.read()) != -1) {
				//System.out.println((char)data);
				out.write(data);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

实验1:利用字符流完成文件的读写操作

package com.liudm.test1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.liudm.test1.FileTest;

public class FileTest {
	public static void main(String[] args) throws IOException {
		FileTest.WritrDoc("/data/liudm.txt");
	}
	
	public static void WritrDoc (String file1) throws IOException{
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(new File(file1));
			bw = new BufferedWriter(fw);
			bw.write("写入++++");
			bw.write("追加++++");
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (bw != null) {
				bw.close();
			}
		}
	}
	
	public static void ReadDoc (String file1) throws FileNotFoundException {
		FileReader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(new File(file1));
			br = new BufferedReader(fr);
			int data = 0;
			while ((data = br.read()) != -1) {
				System.out.println((char)data);
			}
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}


实验2:利用字节流完成文件的读写操作

package com.liudm.demo2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileTest {
	public static void main(String[] args) throws IOException {
		FileTest.WriteDoc("/data/liudmm.txt");
		FileTest.ReadDoc("/data/liudmm.txt");
	}
	
	public static void WriteDoc(String f) throws IOException {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(f);
			out.write(65);
			out.write(115);
			out.write(104);
			out.write(32);
			out.write(105);
			out.write(115);
			out.write(32);
			
			byte [] bs = new byte [20];
			bs[0] = 't';
			bs[1] = 'h';
			bs[2] = 'e';
			bs[3] = ' ';
			bs[4] = 'p';
			bs[5] = 'u';
			bs[6] = 'r';
			bs[7] = 'e';
			bs[8] = 's';
			bs[9] = 't';
			out.write(bs);
			
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
	
	public static void ReadDoc(String f) throws IOException {
		FileInputStream in = null;
		try {
			in = new FileInputStream(f);
			int data = 0;
			while ((data = in.read()) != -1) {
				System.out.println((char)data);
			}
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}
}

练习1:编码实现从C盘拷贝一张图片到D盘

package com.liudm.demo13;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test1 {
	public static void main(String[] args) throws IOException {
		Test1.copy("C:\\subwaymap.jpg","D:\\subwaymap.jpg");
	}

	private static void copy(String start, String end) throws IOException {
		// TODO Auto-generated method stub
		FileInputStream in = new FileInputStream(new File(start));
		FileOutputStream out = new FileOutputStream(new File(end));
		int data = 0;
		try {
			while ((data = in.read()) != -1) {
				out.write(data);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}

     

练习2:编码实现将一个包含大量中文的文件从C盘copy到D盘

package com.liudm.demo13;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test2 {
	public static void main(String[] args) throws IOException {
		FileReader fr = null;
		FileWriter fw = null;
		try {
			fr = new FileReader("C:\\IO流.txt");  //该含有大量中文字符的文件已存在
			fw = new FileWriter("D:\\IO流.txt");
			int data =0;
			while((data = fr.read()) != -1){
				fw.write(data);
			}
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (fw != null) {
				fw.close();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42526141/article/details/82876720