❥ 作为上学年 “Java硬核程序设计实验详解” 系列补充 ❥
目录
❀1. 题目:自定义异常类MyException,该类继承自Exception类
❀3. 题目:利用java I/O流实现学生信息的存储和读取
❀4. 题目:统计英文单词。使用FileReader字符流统计一篇英文中单词
☀️| 一、实验目的
1.了解Java异常处理(exception)的作用。
2.掌握异常处理的设计方法。
3.掌握字节流的基本使用方法。
4.掌握字符流的基本使用方法。
5.能够创建、读写、更新文件
☀️| 二、实验内容
❀1. 题目:自定义异常类MyException,该类继承自Exception类
类中只有含一个字符串参数msg的构造方法,构造方法中只有一条语句super(msg)——调用父类的构造方法。另外,编写自定义类person,类中只有两个私有的变量,一个是字符串类型的姓名,另一个是整型变量age;有两个公有方法void getAge()和setAge(int age),其中setAge(int age)的功能是把参数age的值加到类中的变量age中(但要求age>0,否则抛出自定义异常MyException类的对象),getAge()方法返回age的值。(知识点:异常的概念及体系结构,继承,自定义异常类)
实验结果:
❀2. 题目:使用 数据输出流和输入流 实现如下功能程序
将整型数据和字符串对象通过数据输出流写到文件中。将文件中的整型数据和字符串对象通过数据输出流读出,并在屏幕上显示文件中的内容。(知识点:字节流,异常处理)
实验结果:
❀3. 题目:利用java I/O流实现学生信息的存储和读取
(1)创建学生类Student。
public class Student { private String xh; private String xm; private String xb; private int age; //没有参数的构造函数 【代码1】 //有四个参数的构造函数 【代码2】 //重写equals方法,判断两个学生的学号相同是否相同 【代码3】 } |
(2)新建一个接口StudentDao,该接口中有保存和读取学生信息的方法。
public interface StudentDao { public List<Student> loadStudents() throws Exception; public void saveStudents(Student student) throws Exception; } |
(3)学生数据文件(studata.txt)中的学生数据格式如下:[学号;姓名;性别;年龄]
20130508102;陆晓燕;女;20
20130508103;李雪莹;女;21
20130508104;陆晓博;男;22
20130508105;张云波;男;20
即每个学生数据占一行,数据中每个字段以“;”分隔,对应字段为学号(xh)、姓名(xm)、性别(xb)、年龄(age),其中学号是学生的惟一标识,不存在重复学号的两位学生。字段的设置见第1步的学生类Student。由于学号作为学生的惟一标识,请在Student类中重写方法equals(Object obj)。(为了实现的需要,只要学号相同的两个Student实例将会视为相等)。
(4)创建StudentDao接口的实现类StudentDaoImpl,重写接口中的方法。
public class StudentDaoImpl implements StudentDao { //完成从文件studata.txt读取数据,并将数据转换为Student对象集合 public List<Student> loadStudents() throws Exception { //待完成... 打开文件、读取文件(每读一行处理一行)、关闭文件 } //将一个学生对象写入到文件studata.txt中 public void saveStudents(Student student) throws Exception { } } |
(5)编写测试类,调用StudentDao接口的实现类中的方法完成学生信息的读取,在主程序中输出读取到的学生信息,完成学生信息的增加。
(知识点:字符流/过滤流的使用,面向接口编程,DAO编程模型初步了解,异常处理)
实验结果:
❀4. 题目:统计英文单词。使用FileReader字符流统计一篇英文中单词
要求如下:
①一共出现了多少个单词;②有多少个互不相同的单词;③给出每个单词出现的频率,并将这些单词按频率大小顺序输出到文件words.txt文件中。
(知识点:字符流/过滤流的使用,String常用方法,异常处理)
实验结果:
❀5. 题目:修改本实验第3题(选做题)
将学生数据存储在Excel表格中,使用第三方poi-3.0.1.jar实现从Excel文件中批量导入数据至程序中。
实验结果:(同三)
☀️| 三、实验源代码
⭐️1. 源代码:
package EXPS.Exp07.exp01;
/**
* 班级:19软嵌2
* 学号:20190507223
* 姓名:夏旭
* 实验时间:2020-6-1
* 本程序的功能是:构造自定义异常
*/
public class MyException extends Exception {
//构造函数
public MyException(String msg){
super(msg);
}
}
package EXPS.Exp07.exp01;
public class person {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge (int age)throws MyException {
if(age<=0){
throw new MyException("年龄不合法");
}
this.age = age;
}
}
⭐️2. 源代码:
package EXPS.Exp07;
import java.io.*;
/**
* 班级:19软嵌2
* 学号:20190507223
* 姓名:夏旭
* 实验时间:2020-6-1
* 本程序的功能是:实现文件输入输出
*/
public class Exp07_02_20190507223 {
public static void main(String args[])throws IOException{
try
{ //添加方式创建文件输出流
FileOutputStream fout = new FileOutputStream("out.txt",false);
DataOutputStream dout = new DataOutputStream(fout);
dout.writeInt(48);
dout.writeChars("aaa"+"\n");
dout.writeInt(49);
dout.writeChars("bbb"+"\n");
dout.close();
}
catch (IOException ioe){
ioe.printStackTrace();
}
try
{
FileInputStream fin = new FileInputStream("out.txt");
DataInputStream din = new DataInputStream(fin);
int i = din.read();
while (i!=-1) //输入流未结束时,输入流结束时i 为-1
{
System.out.print((char)i);
i=din.read();
}
din.close();
}
catch (IOException ioe){
ioe.printStackTrace();
}
}
}
⭐️3.(5)源代码:
package EXPS.Exp07.exp03;
import java.util.*;
import EXPS.Exp07.exp03.*;
/**
* 班级:19软嵌2
* 学号:20190507223
* 姓名:夏旭
* 实验时间:2020-6-1
* 本程序的功能是:通过文件流输入输出数据(已实现导入Excel读取数据)
*/
public class Main {
public static void main(String[] args) {
StudentDao x=new StudentDaoImpl();
try {
List<Student> q= x.loadStudents();
x.saveStudents(new Student("2019050109","oldsheep","男",21));
List<Student> res=x.loadStudentsbyExcel();
for(int i=0;i<res.size();i++){
System.out.println(res.get(i).toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package EXPS.Exp07.exp03;
import java.util.Objects;
public class Student {
private String xh;
private String xm;
private String xb;
private int age;
//没有参数的构造函数
public Student() {
}
//有四个参数的构造函数
public Student(String xh, String xm, String xb, int age) {
this.xh = xh;
this.xm = xm;
this.xb = xb;
this.age = age;
}
@Override
public boolean equals(Object o) {
if(o instanceof Student) {
Student node=(Student)o;
return this.xh.equals(node.xh);
}
return false;
}
//重写equals方法,判断两个学生的学号相同是否相同
@Override
public String toString() {
return "Student{" +
"xh='" + xh + '\'' +
", xm='" + xm + '\'' +
", xb='" + xb + '\'' +
", age=" + age +
'}';
}
public String getXh() {
return xh;
}
public String getXm() {
return xm;
}
public String getXb() {
return xb;
}
public int getAge() {
return age;
}
}
package EXPS.Exp07.exp03;
import java.util.List;
public interface StudentDao {
public List<Student> loadStudents() throws Exception;
public void saveStudents(Student student) throws Exception;
public List<Student> loadStudentsbyExcel() throws Exception;
}
package EXPS.Exp07.exp03;
import java.io.*;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class StudentDaoImpl implements StudentDao {
//完成从文件studata.txt读取数据,并将数据转换为Student对象集合
@Override
public List<Student> loadStudents() throws Exception {
List<Student> res=new ArrayList<>();
File srcFile = new File(".\\src\\EXPS\\Exp07\\exp03\\studata.txt");
Reader read = null;
StringBuffer stringBuffer=new StringBuffer();
try {
read=new FileReader(srcFile);
int len=0;
while ((len=read.read())!=-1){
if(len=='\n'){
res.add(buildStudent(stringBuffer));
stringBuffer=new StringBuffer();
}
else{
stringBuffer.append((char)len);
//System.out.println(stringBuffer);
}
}
}
catch (IOException e){
e.printStackTrace();
}
finally {
try {
if(null != read) //创建流可能失败所以判断一下
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//待完成... 打开文件、读取文件(每读一行处理一行)、关闭文件
return res;
}
//将一个学生对象写入到文件studata.txt中
@Override
public void saveStudents(Student student) throws Exception {
FileWriter fw =new FileWriter(".\\src\\EXPS\\Exp07\\exp03\\studata.txt",true);
StringBuffer stringBuffer=new StringBuffer();
stringBuffer.append(student.getXh()+";"+student.getXm()+";"+student.getXb()+";"+student.getAge()+'\n');
fw.write(stringBuffer.toString());
fw.close();
}
public Student buildStudent(StringBuffer s){
s.deleteCharAt(s.length()-1);//删除行末字符
String []list=s.toString().split(";");
return new Student(list[0],list[1],list[2],Integer.parseInt(list[3]));
}
public List<Student> loadStudentsbyExcel() throws Exception{
List<Student> res=new ArrayList<>();
File srcFile = new File(".\\src\\EXPS\\Exp07\\exp03\\studentdata.xls");
InputStream is=new FileInputStream(srcFile);
Workbook workbook=new HSSFWorkbook(is);
for(int i=0;i<workbook.getNumberOfSheets();i++){
Sheet sheet=workbook.getSheetAt(i);
for(int j=1;j<sheet.getPhysicalNumberOfRows();j++){
Row row=sheet.getRow(j);
String []list=new String[4];
for(int k=0;k<row.getPhysicalNumberOfCells();k++){
Cell cell=row.getCell(k);
cell.setCellType(Cell.CELL_TYPE_STRING);
list[k]=cell.getStringCellValue();
}
res.add(new Student(list[0],list[1],list[2],Integer.parseInt(list[3])));
}
}
return res;
}
}
⭐️4. 源代码:
package EXPS.Exp07;
import java.io.*;
import java.util.*;
/**
* 班级:19软嵌2
* 学号:20190507223
* 姓名:夏旭
* 实验时间:2020-6-1
* 本程序的功能是:读入一段英文文章,统计不同字符出现次数并导出
*/
public class Exp07_04_20190507223 {
public static int totword=0;//记录总共单词个数
public static void main(String[] args) {
//创建源
File srcFile = new File("englishparse.txt");
//选择流
Reader read = null;
try {
read = new FileReader(srcFile);
//FileReader读取字符流
char[] buff = new char[1024];
int len = 0;
while((len = read.read(buff)) != -1) {
String str = new String(buff, 0, len);
//System.out.println(str);
str=str.replace(',',' ');
str=str.replace('.',' ');
str=str.replace('\"',' ');
str=str.replace('\n',' ');//去除标点符号,回车等
String []lis=str.split(" ");
List<node> que=getres(lis);
FileOutputStream fout = new FileOutputStream("outEnglishParse.txt",true);
DataOutputStream dout = new DataOutputStream(fout);
dout.writeBytes("totnumis:"+totword+"\n");
dout.writeBytes("differentnumis:"+que.size()+"\n");
dout.writeBytes("wordlist\n");
for(int i=0;i<que.size();i++){
dout.writeBytes(que.get(i).word+" "+que.get(i).num+"\n");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null != read) //创建流可能失败所以判断一下
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static List<node> getres(String [] lis){
HashMap<String,node> hashMap=new HashMap<>();
for(int i=0;i< lis.length;i++){
if(is_word(lis[i])){
totword++;
if(hashMap.containsKey(lis[i])){
hashMap.get(lis[i]).add();
}
else{
hashMap.put(lis[i],new node(lis[i]));
}
}
}
List<node> que=new ArrayList<>();
for(HashMap.Entry<String,node> i:hashMap.entrySet()){
que.add(i.getValue());
}
que.sort(new Comparator<node>() {
@Override
public int compare(node node, node t1) {
return t1.num-node.num;
}
});
return que;
}
public static boolean is_word(String s){
if(s.length()==0) return false;
for(int i=0;i<s.length();i++){
char x=s.charAt(i);
if(x<'A' || x>'z' || (x>'Z' && x<'a')) return false;
}
return true;
}
}
class node{
public String word;
public int num;
public node(String word){
this.word=word;
this.num=1;
}
public void add(){
this.num++;
}
}
☀️| 四、实验总结
通过这次实验,我了解了Java异常处理(exception)的作用。掌握了异常处理的设计方法;字节流的基本使用方法;字符流的基本使用方法,并且能够创建、读写、更新文件。