java文件操作&IO流(超详细,练习案例多!)

磁盘操作

file类

  • String getName()

    获取文件或目录名

  • String getparent()

    获取文件所在的父级目录名称

  • String getParentFile()

    获取文件所在的父级目录对象

  • long length()

    文件长度(内容大小,单位字节)

  • long lastModified()

    最后修改日期

  • getPath / getAbsolutePath() / getCanonicalPath()

文件路径信息: getAbsolutePath()绝对路径 ; getCanonicalPath()规范路径

  • boolean exists()

    文件是否存在

  • boolean delete()

    删除文件

  • boolean isFile()

    判断是否是一个文件

  • boolean isDirectory()

    判断是否为一个目录

  • boolean createNewFile()

    文件创建

  • mkdir()

    创建单层目录

  • mkdirs()

    创建多层目录

  • list() /listFiles()

    遍历目录(递归)

  • File.listRoots()

    磁盘分区(目录)

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class Test01 {
	public static void main(String[] args) throws IOException {
		File f1 = new File("f:\\eclipseIOTest\\test01.txt");
		File f2 = new File("f:\\eclipseIOTest");
		File f3 = new File("f:\\eclipseIOTest\\test02.txt");   //不存在的文件
		File f4 = new File("f:\\eclipseIOTest\\test");          //不存在的目录
		
		System.out.println(f1);
		System.out.printf("[%s]文件的长度是%d\n",f1.getName(),f1.length());
		System.out.printf("[%s]目录的长度是%d\n",f2.getName(),f2.length());
		
		System.out.printf("[%s]文件最后的修改时间:%s\n",f1.getName(),new Date(f1.lastModified()));
		System.out.printf("[%s]目录最后的修改时间:%s\n",f2.getName(),new Date(f2.lastModified()));
		
		//相对路径
		File f5 = new File("./xxx.txt");
		
		//操作路径信息
		//获取文件的绝对路径
		System.out.printf("[%s]文件的绝对路径是【%s】\n",f1.getName(),f1.getAbsolutePath());
		System.out.printf("[%s]文件的绝对路径是【%s】\n",f5.getName(),f5.getAbsolutePath());
		//获取文件的规范路径
		System.out.printf("[%s]文件的规范路径是【%s】\n",f1.getName(),f1.getCanonicalPath());
		System.out.printf("[%s]文件的规范路径是【%s】\n",f5.getName(),f5.getCanonicalPath());
		//获取文件所在的目录的名称
		System.out.printf("[%s]文件的所在目录【%s】\n",f1.getName(),f1.getParent());
		System.out.printf("[%s]文件的所在目录【%s】\n",f1.getName(),f1.getParentFile().getName());
		
		//判断文件或目录是否存在
		System.out.printf("[%s]文件是否存在%s \n",f1.getName(),f1.exists());
		System.out.printf("[%s]目录是否存在%s \n",f2.getName(),f2.exists());
		System.out.printf("[%s]文件是否存在%s \n",f3.getName(),f3.exists());
		System.out.printf("[%s]文件是否存在%s \n",f4.getName(),f4.exists());
		
		//删除文件或目录
		boolean isDelete = f1.delete();
		System.out.printf("[%s]文件删除%s \n",f1.getName(),isDelete);
		
		// 创建文件
		boolean idCreate = f3.createNewFile();
		System.out.printf("[%s]文件创建%s \n",f3.getName(),idCreate);
		
		//创建单层目录
		f4.mkdir();
		System.out.printf("[%s]目录创建 \n",f4.getName());
		//创建多层目录
		File f6 = new File("f:\\eclipseIOTest\\test1\\aa\\bb\\cc");
		f6.mkdirs();
		System.out.printf("[%s]目录创建 \n",f6.getName());
	}
}
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test02 {
	public static void main(String[] args) {
		File root = new File("F:\\eclipseIOTest");
		//获取根目录下的所有子文件(目录)
		//仅包含名称
//		String[] fileNames = root.list();
//		for(String name : fileNames) {
//			System.out.println(name);
//		}
		
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		File[] files = root.listFiles();
		for(File f: files) {
			String type = f.isDirectory() ? "目录":"文件";
			String name = f.getName();
			Long length = f.length();
			String date = fmt.format(new Date(f.lastModified()));
			System.out.printf("【%s】%s,文件大小%d字节,创建日期%s\n",type,name,length,date);
		}
	}
} 
//递归遍历目录
import java.io.File;

public class Test03 {
	public static void main(String[] args) {
		File root = new File("F:\\eclipseIOTest");
		showFileTree(root);
	}
	public static void showFileTree(File dir) {
		File[] files = dir.listFiles();
		for(File f : files) {
			String name = f.getName();
			long lenght = f.length();
			if(f.isFile()) {
				System.out.printf("【文件】%s,文件大小:%d字节 \n" ,name,lenght);
			}else {
				System.out.printf("【目录】%s,包含%d个文件 \n",name,f.list().length);
				showFileTree(f);
			}
		}
	}
}
//磁盘分区目录
import java.io.File;

public class Test04 {
	public static void main(String[] args) {
		//分区
		File[] roots = File.listRoots();
		for(File root : roots) {
			System.out.println("分区:" + root.getPath());
			System.out.println("总容量:" + root.getTotalSpace()/1024/1024/1024);
			System.out.println("空闲容量:" + root.getFreeSpace()/1024/1024/1024);
			System.out.println("可用容量:" + root.getUsableSpace()/1024/1024/1024);
		}
	}
}

files类

  • listFiles()

    遍历目录(非递归)

    1. listFiles()

      • FileFilter()接口:文件过滤器
      import java.io.File;
      import java.io.FileFilter;
      
      public class Test05 {
      	public static void main(String[] args) {
      		File files = new File("C:\\Users\\23039\\Pictures");
      		File[] dir = files.listFiles(new FileFilter() {
      			
      			@Override
      			public boolean accept(File f) {
      				if(f.getName().endsWith(".jpg")||f.getName().endsWith(".png")) {
      					return true;
      				}
      				return false;
      			}
      		});
      		for(File f : dir) {
      			System.out.println(f);
      		}
      	}
      }
      
    2. walkFileTree(文件对象,文件访问器)

      • SimpleFileVisitor:适配器
      import java.io.File;
      import java.io.IOException;
      import java.nio.file.FileVisitResult;
      import java.nio.file.Files;
      import java.nio.file.Path;
      import java.nio.file.Paths;
      import java.nio.file.SimpleFileVisitor;
      import java.nio.file.attribute.BasicFileAttributes;
      
      public class Test06 {
      	public static void main(String[] args) throws IOException {
      		Path root = Paths.get("F:\\eclipseIOTest");
              //SimpleFileVisitor:适配器
      		Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
      			@Override
      			public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
      				File f = dir.toFile();
      				System.out.printf("【目录】%s,包含%d个文件 \n",f.getName(),f.list().length);
      				return FileVisitResult.CONTINUE;
      			}
      			@Override
      			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      				File f = file.toFile();
      				System.out.printf("【文件】%s,文件大小:%d字节 \n" ,f.getName(),f.length());
      				
      				return FileVisitResult.CONTINUE;
      			}
      		});
      	}
      }
      
  • readAllLines()

    读取字符

  • readAllBytes()

    读取字节

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class Test08 {
	public static void main(String[] args) {
		//读取文本文件
		try {
			List<String> lines =  Files.readAllLines(Paths.get("F:\\eclipseIOTest\\test03.txt"));
			for(String In : lines) {
				System.out.println(In);
			}
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		//读取一张图片
		try {
			byte[] bytes = Files.readAllBytes(Paths.get("F:\\eclipseIOTest\\头像.png"));
			for(byte b : bytes) {
				System.out.println(b);
			}
			
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
}
  • write()

    文件写入

    1. 写入字符

    Files.write(Paths.get(“F:\eclipseIOTest\ttt.txt”), list,StandardOpenOption.APPEND)

    • Paths.get(“F:\eclipseIOTest\ttt.txt”):写入文件
    • list:写入内容
    • StandardOpenOption.APPEND:追加
    1. 写入字节
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    import java.util.Arrays;
    import java.util.List;
    
    public class Test09 {
    	public static void main(String[] args) {
            //写入字符
    		List<String> list = Arrays.asList("铁甲小宝","电击小子","猪猪侠","超人强");
    		try {
    			Files.write(Paths.get("F:\\eclipseIOTest\\ttt.txt"), list,StandardOpenOption.APPEND);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		
            //写入字节
    		try {
    			byte[] imageBytes = Files.readAllBytes(Paths.get("C:\\Users\\23039\\Pictures\\图片1.jpg"));
    			Files.write(Paths.get("F:\\eclipseIOTest\\sea.jpg"), imageBytes);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

字节操作(字节流)

输入流InputStream(读)

方法

  • int read()
    1. 读取输入流的下一个字节
    2. 返回读取到的字节,范围(0~255)
    3. 读到末尾,返回-1
  • int read(byte b[ ])
    1. 每次读取N个字节,存入byte[ ]字节数组中
    2. 返回读取长度
    3. 读到末尾,返回-1

实现类

  • FileInputStream类

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class Test10 {
	public static void main(String[] args){
		try(FileInputStream fis = new FileInputStream("F:\\eclipseIOTest\\sea.jpg")) {
			//方式1
//			int data = -1 ;
//			while((data = fis.read()) != -1) {
//				System.out.println(data);
//			}
			//方式2
			byte[] buff = new byte[128];
			int len = -1;
			while ((len = fis.read(buff)) != -1) {
				System.out.printf("本次读取到%d个字节:%s\n",len,Arrays.toString(buff));
			}
			
		} catch(FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
  • BufferedInputStream类

    带有缓冲区的输入流

    创建BufferedInputStream缓冲区输入流默认在内存中创建一个长度为8192字节的byte[] buf

    用于存储读的内容,缓冲区读完会一次性填充满缓冲区,减少对磁盘的访问频率

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

public class Test11 {
	public static void main(String[] args) {
		try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("F:\\eclipseIOTest\\sea.jpg"))) {
			byte[] buf = new byte[128];
			int len = -1 ;
            // 每次从缓冲区中读取128字节
			while((len = bis.read(buf)) != -1) {
				System.out.printf("本次读取到%d个字节:%s\n",len,Arrays.toString(buf));
			}
		}  catch (IOException e) {
			e.printStackTrace();
		} 
	}
}

输出流OutputStream(写)

方法

  • write(int b)

    写入一个字节

  • write(byte b[])

    写入字节数组内所有内容

  • write(byte b[], int off, int len)

    写入字节数组的内容,从off位置开始,长度为len

实现类

  • FileOutStream类

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

  • BufferedOutStream类

    带有缓冲区的输入流

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test13 {
	public static void main(String[] args) {
		try (FileOutputStream fos = new FileOutputStream("F:\\eclipseIOTest\\my.txt",true);
// true:代表追加;默认为false,不追加             
			BufferedOutputStream bos = new BufferedOutputStream(fos)) {	
			bos.write("天王盖地虎".getBytes());
			bos.write("一百八一杯".getBytes());		
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
}

案例一:网络连接输入输出流,下载图片

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Test12 {
	public static void main(String[] args) {
		File f = new File("F:\\eclipseIOTest\\孤注一掷.webp");
		
		try {
            //根据URL网址,创建程序与服务器Connection连接
			URL url = new URL("https://img2.doubanio.com/view/photo/l/public/p2896551721.webp");
			URLConnection connection = url.openConnection();
			
            //通过Connection连接获取InputStream输出流
            //通过输出流,进行读取文件内容
			try(InputStream in = connection.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(in);
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));){
				
				byte[] buff = new byte[1024];
				int len = -1;
				while ((len = bis.read(buff)) != -1) {
					bos.write(buff,0,len);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

案例二:本地复制粘贴图片

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test14 {
	public static void main(String[] args) {
		File f1 = new File("C:\\Users\\23039\\Pictures\\图片3.jpg");
		File f2 = new File("F:\\eclipseIOTest\\复制图片.jpg");
		fileCopy(f1, f2);
	}
	public static void fileCopy(File source , File target) {
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target))) {
			byte[] buff = new byte[2048];
			int len = -1;
			while((len = bis.read(buff)) != -1) {
				bos.write(buff,0,len);
			}	
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
}

字符操作(字符流)

输入流Reader(读)

FileReader类

  • int read()
    1. 读取一个字符
    2. 读取至末尾返回-1
  • int read(char cbuf[])
    1. 读取一个字符数组
    2. 每次返回读取到的字符个数
    3. 读取至末尾(未读取到字符),返回-1

BufferedReader类

  • String readLine( )
    1. 读取一整行
    2. 读取至末尾,返回null
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Test08 {
	//读取文本文件
	public static void main(String[] args) {
		try (BufferedReader reader = new BufferedReader(new FileReader("F:\\eclipseIOTest\\test02.txt"))) {
			//每次读一个字符
//			char firstch = (char)reader.read();
//			System.out.println(firstch);
			
			//每次读取一个字符数组
//			char[] chs = new char[10];
//			reader.read(chs);
//			System.out.println(chs);
			
			
			//每次读一行
//			String line = reader.readLine();
//			System.out.println(line);
			
			//遍历所有行
			String line = null;
			while((line = reader.readLine()) !=null) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

案例:获取网易的界面

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

import javax.net.ssl.HttpsURLConnection;

public class Test10 {
	public static void main(String[] args) {
		//读取网络地址
		try {URL url = new URL("https://www.163.com/");
			HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
			
			try(BufferedReader reader = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream(),Charset.forName("utf-8")));){
				String line = null;
				while((line = reader.readLine()) !=null ) {
					System.out.println(line);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}

输出流Writer(写)

FileWriter类

BufferedWriter类

  • void write(String str)

    写入一整行

  • void newLine( )

创建新行,输出换行符(根据操作系统不同,输出不同的换行符,windows是\r\n,Linux和Mac OS是\n)

案例:向本地文件写入100个UUID的前5位

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;

public class Test09 {
	public static void main(String[] args) {
		try (BufferedWriter writer = new BufferedWriter(new FileWriter("f:\\eclipseIOTest\\aaa.txt"))) {
		
			int count = 0;
			while(count <100) {
				writer.write(UUID.randomUUID().toString().substring(0,5));
				writer.newLine();
				count++;
			}	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Serializable序列化

  • 序列化:ObjectOutputStream类

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

    对象==>输出流==>字节==>文件(网络)

  • 反序列化:ObjectInputStream类

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

    二进制文件==>字节==>输入流 ==>对象

  • serialVersionUID:序列化的版本编号

    写入文件时添加此版本编号,类成员变量发生变化时,反实例化不会出现序列化版本编号不相同,反实例化时本地存储的版本编号和当前版本编号匹配就不会出现报错

Book类

import java.io.Serializable;

// Serializable接口:实现该标记接口,代表Book类的对象,可以被实例化或反实例化
public class Book implements Serializable {
	private static final long serialVersionUID = -11867289724925062L;
	private String bookName;
	private String author;
	private double price;
	private String publisher;
	
	public Book(String bookName, String author, double price,String publisher) {
		super();
		this.bookName = bookName;
		this.author = author;
		this.price = price;
		this.setPublisher(publisher);
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getPublisher() {
		return publisher;
	}
	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}
}

Decorator装饰器模式

装饰器模式可以实现IO流功能叠加

java的IO标准库提供的InputStream根据来源可以包括

  • FileInputStream:从文件读取数据,是最终数据源
  • ServleInputStream:从HTTP请求读取数据,是最终数据源
  • Socker.getInputStream():从TCP连接读取数据,是最终数据源

当我们想给这些最终数据源添加缓冲功能,计算签名功能,加密解码功能等等,可以从最终数据源类派生子类如BufferedFileInputStream,每个子类只实现单一的功能,但既想有缓冲功能又有计算签名功能时,可以使用提供额外附加功能的InputStream,它们均继承自FilterInputStream,如BufferedInputStream,DigestInputStream等

案例:

InputStream file = new FileInputStream("f:\\eclipseIOTest");
InputStream buffered = new BufferedInputStream(file);
InputStream gzip = new GZIPInputStream(buffered);

编写FilterInputStream

访问classpath资源文件

  • classpath资源文件

    放在class文件同级目录下(bin)的文件,访问时不需要关心实际存放的路径,路径以/开头,我们先获取当前的class对象,然后调用getResourceAsStream()就可以从classpath读取任意的资源文件

    import java.io.BufferedInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Arrays;
    
    public class Test02 {
    	public static void main(String[] args) {
    		//访问classpath资源文件
    		try (InputStream in = Test02.class.getResourceAsStream("/test03.txt");
    				BufferedInputStream bis = new BufferedInputStream(in)) {
    			byte[] buff = new byte[128];
    			int len = -1;
    			while((len = bis.read(buff)) != -1) {
    				System.out.println(Arrays.toString(buff));
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  • 读取classpath下的properties文件

    properties文件内容要求: 键值对格式

    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class Test03 {
    	public static void main(String[] args) {
    		//读取classpath下的properties文件  内容要求:键值对格式
    		try (InputStream in = Test03.class.getResourceAsStream("/test04.properties")) {
    			Properties prop = new Properties();
    			prop.load(in);  //通过Properties对象	加载*.properties文件
    		
    			System.out.println("key密钥:"+prop.getProperty("key","0000000"));  // vlaue默认值0000000
    			System.out.println("size大小:"+prop.getProperty("size","0000000"));
    			System.out.println("count数量:"+prop.getProperty("count","0000000"));
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

操作Zip压缩文件

ZipInputStream是一种FilterInputStream,它可以直接读取zip包的内容

  • 写入zip包

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    public class Test04 {
    	public static void main(String[] args) {
    		File root = new File("C:\\Users\\23039\\Pictures");
    		File[] files = root.listFiles();
    		//将root中的文件压缩并写入photo.zip压缩包内
    		try (ZipOutputStream zos = new ZipOutputStream(
    				                new FileOutputStream("F:\\eclipseIOTest\\photo.zip"))) {
    			for(File f : files) {
    				zos.putNextEntry(new ZipEntry(f.getName()));
    				zos.write(Files.readAllBytes(f.toPath()));
    				zos.closeEntry();
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  • 读取zip包

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    
    public class Test05 {
    	//解析压缩包
    	//ZipInputStream:读取Zip压缩文件的输入流
    	public static void main(String[] args) {
    		try (ZipInputStream zis = new ZipInputStream(new FileInputStream("F:\\eclipseIOTest\\photo.zip"))) {
    			ZipEntry entry= null;
    			
    			//创建存储目录  文件名:currentTimeMillis时间戳
    			File dir = new File("F:\\eclipseIOTest\\"+System.currentTimeMillis());
    			dir.mkdir();
    			
    			//遍历压缩包
    			while((entry = zis.getNextEntry()) != null) {
    				//获取压缩包中的每个文件对象(ZipEntry类型的对象)
    				String name = entry.getName();
    				System.out.println(name);
    				
    				// 通过文件输出流,写入指定目录中的文件
    				try(FileOutputStream fos = new FileOutputStream(dir.getAbsoluteFile()+"/"+name)){
    					byte[] buff = new byte[128];
    					int len = -1;
    					while((len = zis.read(buff)) != -1) {
    						fos.write(buff,0,len);
    					}
    				}
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

练习

题目:统计指定目录下的所有文件,将文件后缀名存放在Map的key的位置,并将数量和大小放在value的位置

思路:存放最终结果的Map:Map<String, Map<String, Long>> ,外层的Map的key存放后缀名,value的位置放一个Map,Map中的两个数据key分别是count(数量)和length(大小)

  • 方法一:正常的判断逻辑
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Work3 {
	private static final String KEY_COUNT = "count";
	private static final String KEY_LENGTH = "length";
	
	public static void main(String[] args) throws IOException {
		Path file = Paths.get("F:\\eclipseIOTest");
		Map<String, Map<String, Long>> map = new HashMap<String, Map<String,Long>>();
		
		Files.walkFileTree(file, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

				File f = file.toFile();
				String name = f.getName();
				int index = name.lastIndexOf(".");
				String suffix = name.substring(index);
				//方法1 判断
				if(map.containsKey(suffix)) {
					Map<String, Long> oldMap = map.get(suffix);
					oldMap.put(KEY_COUNT, oldMap.get(KEY_COUNT)+1);
					oldMap.put(KEY_LENGTH,oldMap.get(KEY_LENGTH)+f.length());
					map.put(suffix, oldMap);		
				}else {
					HashMap<String, Long> valMap = new HashMap<String, Long>();
					valMap.put(KEY_COUNT, 1L);
					valMap.put(KEY_LENGTH, f.length());
					map.put(suffix,valMap);
				}
				return FileVisitResult.CONTINUE;
			}
		});
		for(Entry<String, Map<String, Long>> entry:map.entrySet()) {
			System.out.println("后缀名:【"+entry.getKey()+"】");
			System.out.println("统计值:"+entry.getValue());
		}
	}
}
  • 方法二:集合中的merge()方法
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiFunction;

public class Work4 {
	private static final String KEY_COUNT ="count";
	private static final String KEY_LENGTH ="length";
	public static void main(String[] args) throws IOException {
		Path p = Paths.get("f:\\eclipseIOTest");
		Map<String, Map<String, Long>> map = new HashMap<String, Map<String,Long>>();
		
		Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				File f = file.toFile();
				//获取文件名
				String name= f.getName();
				//获取后缀名
				int index = name.lastIndexOf(".");
				if(index>=0) {
					String suffix = name.substring(index);
					HashMap<String, Long> valueMap = new HashMap<String, Long>();
					valueMap.put(KEY_COUNT,1L);
					valueMap.put(KEY_LENGTH,f.length());
					
					//方法2:merge()方法
					map.merge(suffix, valueMap, new BiFunction<Map<String,Long>, Map<String,Long>, Map<String,Long>>() {

						@Override
						public Map<String, Long> apply(Map<String, Long> t, Map<String, Long> u) {
							HashMap<String, Long> newValMap = new HashMap<String, Long>();
							newValMap.put(KEY_COUNT, t.get(KEY_COUNT)+u.get(KEY_COUNT));
							newValMap.put(KEY_LENGTH, t.get(KEY_LENGTH)+ u.get(KEY_LENGTH));
							return newValMap;
						}
					});
				}
				return FileVisitResult.CONTINUE;
			}
		});
		for(Entry<String, Map<String, Long>> entry:map.entrySet()) {
			System.out.println("后缀名:【"+entry.getKey()+"】");
			System.out.println("统计值:"+entry.getValue());
		}
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeMonkey-D

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值