0501显示目录或文件的属性
代码
ShowFile
package ex501.file;
import java.io.File;
import java.util.Date;
public class ShowFile {
private File file;
public ShowFile(String fileName) {
this.file = new File(fileName);
}
//统计目录下文件个数
public int getFileNumber(File directory){
int num = 0;
File[] files = directory.listFiles();
if (files != null) {
for (File f : files) {
if (f.isFile()) {
num++;
} else {//是目录的话,访问目录下的文件
num+=getFileNumber(f);
}
}
}
return num;
}
//统计目录下目录个数
public int getDirectoryNumber(File directory){
int num = 0;
File[] files = directory.listFiles();
if(files != null){
for (File f : files) {
if (f.isDirectory()) {
num++;
num+=getDirectoryNumber(f);
}
}
}
return num;
}
//统计目录下文件总大小
public long getDirectorySize(File directory){
long size = 0;
File[] files = directory.listFiles();
if(files != null){
for (File f : files) {
if (f.isFile()) {
size += f.length();
} else {
size += getDirectorySize(f);
}
}
}
return size;
}
public void show() {
if(file.isDirectory()){
System.out.println("目标名称:"+file.getName());
System.out.println("-----------------");
System.out.println("目标类型:目录");
System.out.println("所在位置:"+file.getAbsolutePath());
System.out.println("目录大小:"+getDirectorySize(file)+"字节");
System.out.println("修改时间:"+new Date(file.lastModified()));
System.out.println("包含文件:"+getFileNumber(file)+"个");
System.out.println("包含目录:"+getDirectoryNumber(file)+"个");
System.out.println("目标属性:");
System.out.println(" 可读:"+file.canRead());
System.out.println(" 可写:"+file.canWrite());
System.out.println(" 可运行:"+file.canExecute());
System.out.println(" 隐藏:"+file.isHidden());
}
else if (file.isFile()){
System.out.println("目标名称:"+file.getName());
System.out.println("-----------------");
//获取目标文件类型,例如Main.java文件类型为.java
String type = file.getName().substring(file.getName().lastIndexOf("."));
System.out.println("目标类型:文件("+type+")");
System.out.println("所在位置:"+file.getAbsolutePath());
System.out.println("文件大小:"+file.length()+"字节");
System.out.println("修改时间:"+new Date(file.lastModified()));
System.out.println("目标属性:");
System.out.println(" 可读:"+file.canRead());
System.out.println(" 可写:"+file.canWrite());
System.out.println(" 可运行:"+file.canExecute());
System.out.println(" 隐藏:"+file.isHidden());
}
else {
System.out.println("["+file.getName()+ "]不是文件或目录名称");
}
}
}
Main
package ex501;
import ex501.file.ShowFile;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入一个文件名或目录名:");
String fileName = input.nextLine();
ShowFile showFile = new ShowFile(fileName);
showFile.show();
}
}
0502统计Java源程序文件中关键字的使用次数
代码
package ex502.file;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class KeywordsCount {
private List<String> keywords;
private Map<String, Integer> keywordsCount;
public KeywordsCount() {
this.keywords = new ArrayList<>();
this.keywordsCount = new HashMap<>();
}
//读取keywords.txt关键字
public void readKeywords(File file){
try(var reader = Files.newBufferedReader(file.toPath())){
String line;
while((line = reader.readLine()) != null){//读取每一行
keywords.add(line.trim());
keywordsCount.put(line.trim(), 0);
}
} catch (IOException e) {//读取失败
System.err.println("读取失败:"+e.getMessage());
System.exit(1);
}
}
//输入文件名,统计其中关键字出现次数
public void countKeywords(File file){
try(var reader = Files.newBufferedReader(file.toPath())){
String line;
boolean inBlockComment = false;//是否在注释中
while((line = reader.readLine()) != null){
line = line.trim();
if (inBlockComment) {//在注释中
if (line.contains("*/")) {//到达注释尾
inBlockComment = false;
line = line.substring(line.indexOf("*/") + 2).trim();//截取注释尾后的内容
} else {
continue; // 跳过整个行,如果仍在注释中
}
}
if (line.startsWith("/*")) {//注释的开始
inBlockComment = true;//在注释中
if (line.contains("*/")) {
inBlockComment = false;
line = line.substring(line.indexOf("*/") + 2).trim();
} else {
continue; // 跳过整个行,如果它开始了一个块注释
}
}
if (line.startsWith("//")) {
continue; // 跳过单行注释
}
for(String keyword : keywords){
Pattern pattern = Pattern.compile("\\b"+keyword+"\\b");
Matcher matcher = pattern.matcher(line);
while(matcher.find()){//找到关键字+1
keywordsCount.put(keyword, keywordsCount.get(keyword)+1);
}
}
}
} catch (IOException e) {
System.err.println("读取失败:"+e.getMessage());
System.exit(1);
}
}
//把统计结果存储到文本文件,文件名为“keywords-源程序文件名.txt”,文本文件中每行一个关键字和出现次数,按关键字升序排序
public void writeKeywordsCount(File file){
try(var writer = Files.newBufferedWriter(Paths.get("Keywords-"+file.getName()+".txt"))){
keywordsCount.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEach(entry -> {
try {
writer.write(entry.getKey() + " " + entry.getValue() + "\n");
} catch (IOException e) {
System.err.println("写入失败:"+e.getMessage());
System.exit(1);
}
});
} catch (IOException e) {
System.err.println("写入失败:"+e.getMessage());
System.exit(1);
}
}
//查看使用次数排名(降序)前n位的关键字并输出。关键字使用相同时,按关键字升序排序
public void showKeywordsCount(int n){
keywordsCount.entrySet().stream()
.sorted((entry1, entry2) -> {
if(entry1.getValue().equals(entry2.getValue())){
return entry1.getKey().compareTo(entry2.getKey());
}else{
return entry2.getValue().compareTo(entry1.getValue());
}
})
.limit(n)
.forEach(entry -> System.out.println(entry.getKey() + ":" + entry.getValue()));
}
}
package ex502;
import ex502.file.KeywordsCount;
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
KeywordsCount keywordsCount = new KeywordsCount();
System.out.print("输入关键字文件名:");
String fileName1 = input.nextLine();
File file1 = new File(fileName1);
keywordsCount.readKeywords(file1);
System.out.print("输入Java源程序文件名:");
String fileName2 = input.nextLine();
File file2 = new File(fileName2);
keywordsCount.countKeywords(file2);
keywordsCount.writeKeywordsCount(file2);
System.out.println(file2.getName()+"的关键字使用次数已经存放到文件Keywords-"+file2.getName()+"中.");
System.out.print("需要查看排名前几位(范围:1-51)的关键字?");
int n = input.nextInt();
keywordsCount.showKeywordsCount(n);
}
}
0503简易地址簿管理程序
代码
Address
package ex503.address;
import java.io.Serializable;
public class Address implements Serializable {
private String name;
private String province;
private String city;
private String postcode;
private String detail_address;
public Address(String name, String province, String city, String postcode, String detail_address) {
this.name = name;
this.province = province;
this.city = city;
this.postcode = postcode;
this.detail_address = detail_address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getDetail_address() {
return detail_address;
}
public void setDetail_address(String detail_address) {
this.detail_address = detail_address;
}
@Override
public String toString() {
return "姓名:" + name + ",省份:" + province + ",城市:" + city + ",邮政编码:" + postcode + ",详细地址:" + detail_address;
}
}
AddressBook
package ex503.address;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class AddressBook implements Serializable {
private ArrayList<Address> addresses;
public AddressBook() {
this.addresses = new ArrayList<>();
}
//读取文件地址簿,文件名为“address_book.dat”,如果读取失败则创建一个新的地址簿对象
public AddressBook readAddress(){
ArrayList<Address> addresses = new ArrayList<>();
try (FileInputStream fis = new FileInputStream("address_book.dat");
ObjectInputStream ois = new ObjectInputStream(fis)){
while (fis.available() > 0){
Address address = (Address) ois.readObject();
addresses.add(address);
}
this.addresses = addresses;
return this;
} catch (IOException | ClassNotFoundException e) {//读取失败或者文件不存在
System.err.println("读取失败:"+e.getMessage());
return new AddressBook();//创建一个新的地址簿对象
}
}
//保存地址簿到文件
public void saveAddress(){
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("address_book.dat"))){
//oos.writeObject(this);
for (Address address : addresses){
oos.writeObject(address);
}
System.out.println("保存成功!");
} catch (IOException e) {
System.err.println("保存失败:"+e.getMessage());
}
}
//列出所有地址
public void showAllAddress(){
System.out.println("序号 | 姓名 | 省份 | 城市 | 邮政编码 | 详细地址");
System.out.println("--------------------------------------------");
for (int i = 0; i < addresses.size(); i++){
Address address = addresses.get(i);
System.out.printf("%d | %s | %s | %s | %s | %s\n",i+1,address.getName(),address.getProvince(),address.getCity(),address.getPostcode(),address.getDetail_address());
}
System.out.println("--------------------------------------------");
System.out.println("共["+addresses.size()+"]条数据");
}
//添加地址
public void addAddress(){
Scanner input = new Scanner(System.in);
System.out.print("输入姓名:");
String name = input.nextLine();
System.out.print("输入省份:");
String province = input.nextLine();
System.out.print("输入城市:");
String city = input.nextLine();
System.out.print("输入邮政编码:");
String postcode = input.nextLine();
System.out.print("输入详细地址:");
String detail_address = input.nextLine();
Address address = new Address(name,province,city,postcode,detail_address);
addresses.add(address);
System.out.println("添加成功!");
}
//查找地址
public void findAddress(){
Scanner input = new Scanner(System.in);
System.out.print("输入要查找地址的姓名:");
String name = input.nextLine();
System.out.println("序号 | 姓名 | 省份 | 城市 | 邮政编码 | 详细地址");
System.out.println("--------------------------------------------");
int i = 0;
for (Address address : addresses){
if(address.getName().equals(name)){
System.out.printf("%d | %s | %s | %s | %s | %s\n",++i,address.getName(),address.getProvince(),address.getCity(),address.getPostcode(),address.getDetail_address());
}
}
System.out.println("--------------------------------------------");
System.out.println("共["+i+"]条数据");
}
//删除地址
public void deleteAddress(){
ArrayList<Address> tem_addresses = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("输入要删除地址的姓名:");
String name = input.nextLine();
System.out.println("序号 | 姓名 | 省份 | 城市 | 邮政编码 | 详细地址");
System.out.println("--------------------------------------------");
int i = 0;
for (Address address : addresses){
if(address.getName().equals(name)){
tem_addresses.add(address);
System.out.printf("%d | %s | %s | %s | %s | %s\n",++i,address.getName(),address.getProvince(),address.getCity(),address.getPostcode(),address.getDetail_address());
}
}
System.out.println("--------------------------------------------");
System.out.println("共["+i+"]条数据");
System.out.print("输入要删除地址的序号:");
int index = input.nextInt();
addresses.remove(tem_addresses.get(index-1));
}
//修改地址
public void setAddresses(){
ArrayList<Address> tem_addresses = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("输入要修改地址的姓名:");
String name = input.nextLine();
System.out.println("序号 | 姓名 | 省份 | 城市 | 邮政编码 | 详细地址");
System.out.println("--------------------------------------------");
int i = 0;
for (Address address : addresses){
if(address.getName().equals(name)){
tem_addresses.add(address);
System.out.printf("%d | %s | %s | %s | %s | %s\n",++i,address.getName(),address.getProvince(),address.getCity(),address.getPostcode(),address.getDetail_address());
}
}
System.out.println("--------------------------------------------");
System.out.println("共["+i+"]条数据");
System.out.print("输入选择的地址序号:");
int index = input.nextInt();
//消除缓冲区的回车符
input.nextLine();
System.out.println("姓名:");
System.out.println(" 原值:"+tem_addresses.get(index-1).getName());
System.out.print(" 输入新值:");
String new_name = input.nextLine();
if (new_name.equals(""))new_name = tem_addresses.get(index-1).getName();
System.out.println("省份:");
System.out.println(" 原值:"+tem_addresses.get(index-1).getProvince());
System.out.print(" 输入新值:");
String new_province = input.nextLine();
if (new_province.equals(""))new_province = tem_addresses.get(index-1).getProvince();
System.out.println("城市:");
System.out.println(" 原值:"+tem_addresses.get(index-1).getCity());
System.out.print(" 输入新值:");
String new_city = input.nextLine();
if (new_city.equals(""))new_city = tem_addresses.get(index-1).getCity();
System.out.println("邮政编码:");
System.out.println(" 原值:"+tem_addresses.get(index-1).getPostcode());
System.out.print(" 输入新值:");
String new_postcode = input.nextLine();
if (new_postcode.equals(""))new_postcode = tem_addresses.get(index-1).getPostcode();
System.out.println("详细地址:");
System.out.println(" 原值:"+tem_addresses.get(index-1).getDetail_address());
System.out.print(" 输入新值:");
String new_detail_address = input.nextLine();
if (new_detail_address.equals(""))new_detail_address = tem_addresses.get(index-1).getDetail_address();
Address address = new Address(new_name,new_province,new_city,new_postcode,new_detail_address);
addresses.set(addresses.indexOf(tem_addresses.get(index-1)),address);
System.out.println("修改地址成功!");
}
//菜单
public void menu(){
Scanner input = new Scanner(System.in);
readAddress();
while (true){
System.out.println("---功能选项---");
System.out.println("1.地址列表");
System.out.println("2.查找地址");
System.out.println("3.增加地址");
System.out.println("4.删除地址");
System.out.println("5.修改地址");
System.out.println("0.退出");
System.out.println("----------------");
System.out.print("请输入选项号:");
int choice = input.nextInt();
switch (choice){
case 1:
showAllAddress();
break;
case 2:
findAddress();
break;
case 3:
addAddress();
break;
case 4:
deleteAddress();
break;
case 5:
setAddresses();
break;
case 0:
saveAddress();
input.close();
System.exit(0);
default:
System.out.println("输入错误,请重新输入!");
}
}
}
}
Main
package ex503;
import ex503.address.AddressBook;
public class Main{
public static void main(String[] args) {
AddressBook addressBook = new AddressBook();
addressBook.menu();
}
}