方法一:显示星期、月份以及具体时间
练习6
一、练习目的
1.熟悉File类使用;
2.了解常用集合类;
二、练习内容
1.利用File类的方法,1)获得某已有文件的最后修改时间,以年月日的显示输出,如2017-11-04;2)删除某一指定文件,并重新创建该文件,并设置其为只读。
2. 将5个学生的学号和姓名,存储在HashMap类型的集合中;输入一个学号,查询该学号的学生在不在该集合中,在则输出该学生姓名.
第一题代码:
方法一:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LianXi6_1 {
public static void main(String[] args) throws IOException{
File testfile = new File("D://a.txt");
FileOutputStream f1 = new FileOutputStream(testfile);
long time = testfile.lastModified();
Date d = new Date(time);
Format SimpleDateFormat = new SimpleDateFormat("E dd MMM yyyy hh:ss a");
String dateString = SimpleDateFormat.format(d);
System.err.println(testfile.getName()+"最后修改时间:"+dateString);
f1.close();
testfile.delete();
File testfile2 = new File("D://a.txt");
FileOutputStream ff = new FileOutputStream(testfile2);
testfile2.setReadOnly();
ff.close();
}
}
(方法一显示星期、月份以及具体时间)
方法二:
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class LianXi6_11 {
public static void main(String[] args) throws IOException{
File testfile = new File("D://a.txt");
long time = testfile.lastModified();
Date d = new Date(time);
Format SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(testfile.lastModified());
String time1 = SimpleDateFormat.format(cal.getTime());
System.out.println(testfile.getName()+"最后修改时间:"+time1);
}
}
方法二直接显示年月日以及具体时间
第二题:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Scanner;
import java.util.HashMap;
public class LianXi6_22 {
public static void main(String[] args) {
//创建一个HashMap对象
HashMap<String, Integer> stus = new HashMap<>();
//向这个HashMap里面添加元素
stus.put("老大",1801001);
stus.put("老二",1801002);
stus.put("老三",1801003);
stus.put("老四",1804004);
stus.put("老五",1804005);
//提取单个学生成绩
System.out.println("请输入学生姓名:");
Scanner scanner = new Scanner(System.in);
String key = scanner.next();
//判断用户输入的人名是否被包含在map里面,如果在,就打印出来,如果不在就告知不在
if (stus.containsKey(key)) {
System.out.println("该学生的学号是" + stus.get(key));
} else {
System.out.println("这个集合里没有这个人");
}
System.out.println("--------集合内的学生名单为-------");
//用key的集合遍历该Map--增强for
Set set = stus.entrySet();
for (Object o : set) {
Map.Entry me = (Map.Entry) o;
String key1 = (String) me.getKey();
int value = (int) me.getValue();
System.out.println(key1+"的成绩是:"+value);
}
}
}
结论:熟悉了file类和HsahMap的基本操作,在编译运行过程中出现一下小bug,一番调试之后可以执行,很有收获!