0.字节流与二进制文件
我的代码
import java.io.*; class Student { private int id; private String name; private int age; private double grade; public Student(){ } public Student(int id, String name, int age, double grade) { this.id = id; this.setName(name); this.setAge(age); this.setGrade(grade); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { if (name.length()>10){ throw new IllegalArgumentException("name's length should <=10 "+name.length()); } this.name = name; } public int getAge() { return age; } public void setAge(int age) { if (age<=0){ throw new IllegalArgumentException("age should >0 "+age); } this.age = age; } public double getGrade() { return grade; } public void setGrade(double grade) { if (grade<0 || grade >100){ throw new IllegalArgumentException("grade should be in [0,100] "+grade); } this.grade = grade; } @Override public String toString() { return "[id=" + id + ", name=" + name + ", age=" + age + ", grade=" + grade + "]"; } } public class Main { public static void main(String[] args) { String fileName="d:\\test\\student.data"; try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(fileName)))//FileOutputStream把数据写入本地文件 { Student st=new Student(1,"wu",18,85); dos.writeInt(st.getId());// 将int类型的值写入到“数据输出流”中, int占4个字节 dos.writeUTF(st.getName());// 将UTF-8类型的值写入到“数据输出流”中 dos.writeInt(st.getAge()); dos.writeDouble(st.getGrade());// 将double类型的值写入到“数据输出流”中 } catch (FileNotFoundException e) { e.printStackTrace();//获捕异常的语句,在命令行打印异常信息在程序中出错的位置及原因 } catch (IOException e) { e.printStackTrace(); } try(DataInputStream dis=new DataInputStream(new FileInputStream(fileName))) { int id=dis.readInt(); String name=dis.readUTF();// 从“数据输入流”中读取“无符号的short类型”的值: UTF-8输入流的前2个字节是数据的长度 int age=dis.readInt(); double grade=dis.readDouble(); Student stu=new Student(id,name,age,grade); System.out.println(stu); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果
我的总结
1.二进制文件与文本文件的区别:
二进制文件一般是可执行程序、图形、图像、声音等,需要不同(对应)的软件来打开;文本文件储存字符变量,用普通的编辑器如记事本、NotePad++就可以读写。二进制文件读写是将内存里面的数据直接读写入文本中,而文本文件则是将数据先转换成了字符串,再写入到文本中。
2.try...catch...finally注意事项
try、catch、finally语句中,如果只有try中有返回值,则通过finally或者catch中对返回值修改,都不会影响返回值;如果finally块中有return 语句,则返回try或catch中的返回语句忽略。
3.使用try..with...resouces关闭资源
try(FileInputStream fis = new FileInputStream("filename"))
{
fis.read();
}catch (IOException e) {
e.printStackTrace();
}
1.字符流与文本文件
我的代码
1.使用BufferedReader从编码为UTF-8的文本文件中读出学生信息,并组装成对象然后输出
import java.io.*; import java.util.ArrayList; import java.util.List; class Student { ...... } public class Main { public static void main(String[] args) { String fileName="d:\\test\\Students.txt"; List<Student> stuList = new ArrayList<>(); try( FileInputStream fis=new FileInputStream(fileName); InputStreamReader isr=new InputStreamReader(fis, "UTF-8"); BufferedReader br=new BufferedReader(isr)) { String line=null; while((line=br.readLine())!=null) { String[] tokens=line.split("\\s+");//String的split方法使用\\s+可以使用多个空格作为分隔符 int id=Integer.parseInt(tokens[0]); String name=tokens[1]; int age=Integer.parseInt(tokens[2]); double grade=Double.parseDouble(tokens[3]); Student stu=new Student(id,name,age,grade); stuList.add(stu); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println(stuList); }
}
运行结果
2.编写public static ListreadStudents(String fileName)
3.使用PrintWriter将Student对象写入文本文件
import java.io.*; class Student { ...... } public class Main { public static void main(String[] args) { String fileName="d:\\test\\Students.txt"; try( FileOutputStream fos=new FileOutputStream(fileName,true); OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8"); PrintWriter pw=new PrintWriter(osw)) { pw.println(); pw.print("4 刘星 17 90");//id name age grade } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
运行结果
我的结论
在进行任务1的实验时,运行结果中名字输出总是出现乱码,通过修改workspace的Text file encoding为UTF-8编码并且使用Notepad++打开Students.txt将其也改为UTF-8编码,解决了乱码的问题。
在进行任务3的实验时,使用PrintWriter将Student对象写入文本文件会覆盖之前的数据,通过询问同学及搜索相关资料,在构造FileOutputStream时设置为true表示追加内容,就不会对原文件进行覆盖。
2.缓冲流(结合使用JUint进行测试)
我的代码
import java.io.*; import java.util.*; public class Stream { public static void main(String[] args) { String fileName="d:\\test\\data.txt"; try (PrintWriter pw = new PrintWriter(fileName);) { Random num=new Random(); num.setSeed(100); double sum=0; double time; for (int i = 0; i < 1000_0000; i++) { int n=num.nextInt(10); sum+=n; pw.println(n); } time=sum/1000_0000; System.out.format("%.3f", time); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
import java.io.*; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class JUnitTest{ String fileName="d:\\test\\data.txt"; @Test void testScannerRead() { try ( FileInputStream fis = new FileInputStream(fileName); Scanner sc=new Scanner(fis)) { while(sc.hasNextInt()) { sc.nextInt(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); }finally { System.out.println("testScanner end"); } } @Test void testBufferedReader() { try ( FileReader fr = new FileReader(fileName); BufferedReader br=new BufferedReader(fr)) { String line=null; while((line=br.readLine())!=null) { } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); }finally { System.out.println("testBuffered end"); } } }
运行结果
我的总结
对于使用JUnit进行测试的方法使用的很少,不熟悉,因此在实验过程中耗费较多时间也出了较多的问题,通过询问同学以及查看相关资料逐步解决。
6.正则表达式
我的代码
1.如何判断一个给定的字符串是否是10进制数字格式?尝试编程进行验证。
import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; public class Suit { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String patternImgString = "[+-]?[0-9]+"; Pattern pattern=Pattern.compile(patternImgString); Matcher matcher=null; while(sc.hasNext()) { String str=sc.next(); matcher=pattern.matcher(str); System.out.println(matcher.matches()); } sc.close(); } }
运行结果
2.修改HrefMatch.java
匹配网页中的数字字符串
import java.io.*; import java.util.regex.*; /** * This program displays all URLs in a web page by matching a regular expression that describes the * <a href=...> HTML tag. Start the program as <br> * java HrefMatch URL * @version 1.01 2004-06-04 * @author Cay Horstmann */ public class HrefMatch { public static void main(String[] args) { try { String fileName="d:\\test\\集美大学-计算机工程学院.htm"; InputStreamReader in = new InputStreamReader(new FileInputStream(fileName)); StringBuilder input = new StringBuilder(); int ch; while ((ch = in.read()) != -1) input.append((char) ch); String patternString = "[+-]?[0-9]+(\\.\\d+)?"; String patternImgString = "[+-]?[0-9]+"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String match = input.substring(start, end); System.out.println(match); } } catch (IOException e) { e.printStackTrace(); } catch (PatternSyntaxException e) { e.printStackTrace(); } } }
运行结果
匹配网页中的图片字符串
import java.io.*; import java.net.*; import java.util.regex.*; public class HrefMatch { public static void main(String[] args) { try { String fileName="d:\\test\\集美大学-计算机工程学院.htm"; InputStreamReader in = new InputStreamReader(new FileInputStream(fileName)); StringBuilder input = new StringBuilder(); int ch; while ((ch = in.read()) != -1) input.append((char) ch); String patternImgString = "img\\s[a-zA-Z]+=\".*.(gif|png|jpg|jpeg)\""; Pattern pattern = Pattern.compile(patternImgString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String match = input.substring(start, end); System.out.println(match); } } catch (IOException e) { e.printStackTrace(); } catch (PatternSyntaxException e) { e.printStackTrace(); } } }
运行结果
我的总结
同进行字符流与文本文件时一样,需要将集美大学-计算机工程学院.htm用Notepad++打开使用UTF-8编码才能得出上述运行结果。