练习题(二)

该代码示例展示了如何使用Java生成并存储双色球数据到Map集合中,键为颜色,值为排序后的数字。接着,通过递归方法遍历指定目录下的所有文件和文件夹。最后,演示了如何复制一个小说文件,处理可能的IOException。
摘要由CSDN通过智能技术生成

紧接上文的练习题

(三)生成双色球存入Map集合,key是颜色,value是排序后的球,效果如下
a)红球:[1,2,3,4,5,6]
b)蓝球:[7]

import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class Demo03 {
	public static void main(String[] args) {
		Random random = new Random();
		TreeSet<Integer> red = new TreeSet<Integer>();
		TreeSet<Integer> blue = new TreeSet<Integer>();
		while (red.size() < 6) {
			red.add(random.nextInt(33) + 1);
		}
		blue.add(random.nextInt(16) + 1);
		HashMap<String, Set<Integer>> balls = new HashMap<String, Set<Integer>>();
		balls.put("蓝色", blue);
		balls.put("红色", red);
		System.out.println(balls);
	}
}

4.递归获取所有文件和文件夹

public class Demo04 {
	public static void main(String[] args) {
		// (四)递归获取所有文件和文件夹
		//"D:\\Files":自己文件的目录
		File file = new File("D:\\Files");
		look(file);
	}
	public static void look(File file) {
		File[] files = file.listFiles();
		for (File f : files) {
			if (f.isFile()) {
				System.out.println("文件:" + f);
			} else {
				System.out.println("文件夹:" + f);
				look(f);
			}
		}
	}
}

(五)编写代码复制一个小说文件

public class Demo05 {
	public static void main(String[] args) {
		// (五)编写代码复制一个小说文66件
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("小说名");
			fos = new FileOutputStream("桌面");
			@SuppressWarnings("unused")
			int len = -1;
			byte[] b = new byte[1024];
			while ((len = fis.read()) != -1) {
				fos.write(b);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (fis!=null) {				
					fis.close();
				}
				if (fos!=null) {					
					fos.close();		
			      }
			} catch (IOException e) {
				e.printStackTrace();
			}		
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值