201521123044 《Java程序设计》第12周学习总结

1. 本章学习总结

1.1 以你喜欢的方式(思维导图或其他)归纳总结多流与文件相关内容。

2. 书面作业

将Student对象(属性:int id, String name,int age,double,grade)写入文件student.data、从文件读出显示。

1.字符流与文本文件:使用 PrintWriter(写),BufferedReader(读)

  • 1.1 生成的三个学生对象,使用PrintWriter的println方法写入student.txt,每行一个学生,学生的每个属性之间用|作为分隔。使用Scanner或者BufferedReader将student.txt的数据读出。(截图关键代码,出现学号)
//PrintWriter(写)
try  {
	       PrintWriter out = new PrintWriter("student.txt");
	       writeData(stu, out);
	       out.close();
	       Scanner in = new Scanner(new FileReader("student.txt"));
	       Student[]  newStudent = readData(in);
	       in.close();
	       for (Student e : newStudent)
	          System.out.println(e);
	    }
	    catch (IOException exception)
	    {
	       exception.printStackTrace();
	    }
	 }
//Scanner 读数据
public void readData(Scanner in)
		   {
		      String line = in.nextLine();
		      String[] tokens = line.split("\\|");
		      id = Integer.parseInt(tokens[0]);
		      name = tokens[1];
		      age = Integer.parseInt(tokens[2]);
		      grade = Double.parseDouble(tokens[3]);
	
	   }

控制台运行结果:

文件写入显示:

  • 1.2 生成文件大小多少?分析该文件大小

  • 1.3 如果调用PrintWriter的println方法,但在后面不close。文件大小是多少?为什么?

    如图所示,文件大小为0字节,因为close()方法可以自动调用flush()来刷新,如果调用PrintWriter的println方法,但在后面没有close(),数据在缓冲区中导致数据丢失。也就是说数据写到缓冲区上,还未写到文件上。

2.交替执行

  • 2.1使用PrintWriter往文件里写入1千万行(随便什么内容都行),然后对比使用BufferedReader与使用Scanner从该文件中读取数据的速度(只读取,不输出),使用哪种方法快?请详细分析原因?提示:可以使用junit4对比运行时间

    结论:用BufferedReader比Scanner速度快很多,因为使用缓冲可以减少IO次数,可以防止每次读取时都得进行实际的读操作。其实Scanner也有缓冲区,但是相比于BufferedReader要小不少。
  • 2.2 将PrintWriter换成BufferedWriter,观察写入文件的速度是否有提升。记录两者的运行时间。试分析原因。

    写入文件的速度有提升。
    分析:因为在构造BufferedWriter的时候有一个方法是可以规定缓冲区大小的,BufferedWriter可以缓冲各个字符,从而提供单个字符,数组和字符串的高效写入。也就是说BufferedWriter是带有缓冲区的而PrintWriter没有。

3. 字符编码

  • 3.1 现有EncodeTest.txt文件,该文件使用UTF-8编码。使用FileReader与BufferedReader将EncodeTest.txt的文本读入并输出。是否有乱码?为什么会有乱码?如何解决?(截图关键代码,出现学号)
//使用FileReader与BufferedReader将EncodeTest.txt的文本读入并输出:
//关键代码:
public static void main(String[] args) throws Exception  {
		
		//201521123044
		FileReader  a = new FileReader("EncodeTest.txt");
		BufferedReader b = new BufferedReader(a);
		try {
			String line = null;
			while((line = b.readLine())!= null)
				System.out.println(line);
		} finally {
			if(b!=null) {
				b.close();
			}
		}
	}

运行结果:

代码改进:

//关键代码:
public static void main(String[] args) throws Exception {
		// 201521123044
		BufferedReader b =null;
		try {
			FileInputStream m =  new FileInputStream("EncodeTest.txt");
			InputStreamReader n = new InputStreamReader(m,"UTF-8");
			b = new BufferedReader(n);
			String line = null;
			while((line = b.readLine())!=null)
				System.out.println(line);
			
		} finally {
			if(b!=null) {
				b.close();
			}
		}
	}

运行结果:

  • 3.2 编写一个方法convertGBK2UTF8(String src, String dst),可以将以GBK编码的源文件src转换成以UTF8编码的目的文件dst。
//关键代码:
public static void convertGBK2UTF8(String src, String dst) throws IOException {
		// 201521123044
		BufferedReader b = null;
		OutputStreamWriter out = null;
		BufferedWriter outfile = null;
		try {
			b = new BufferedReader(new InputStreamReader(new FileInputStream(src),"UTF-8"));
			out = new OutputStreamWriter(new FileOutputStream(dst),"UTF-8");
			outfile = new BufferedWriter(out);
			String line =null;
			while((line = b.readLine())!=null) {
				outfile.write(line);
				outfile.newLine();
			}
		
		
		
		}finally {
			if(b!=null) {
				b.close();
				outfile.close();
			}
		}
	}

4. 字节流、二进制文件:DataInputStream, DataOutputStream、ObjectInputStream

  • 4.1 参考DataStream目录相关代码,尝试将三个学生对象的数据写入文件,然后从文件读出并显示。(截图关键代码,出现学号)
// 201521123044
		Student[] stu = new Student[3];
	    stu[0] = new Student(2015211044, "张三",18,2);
	    stu[1] = new Student(2015211061,"李四",20,1);
	    stu[2] = new Student(2015211025,"王五", 21,4);
		try
	    {
	       // save all employee records to the file employee.dat
	       PrintWriter out = new PrintWriter("student.txt");
	       writeData(stu, out);
	       out.close();

	       // retrieve all records into a new array
	       Scanner in = new Scanner(new FileReader("student.txt"));
	       Student[]  newStudent = readData(in);
	       in.close();
	     
	       // print the newly read employee records
	       for (Student e : newStudent)
	          System.out.println(e);
	    }
	    catch (IOException exception)
	    {
	       exception.printStackTrace();
	    }
	 }
	private static void writeData(Student[] students, PrintWriter out) throws IOException {
		// TODO Auto-generated method stub
		out.println(students.length);
		for (Student e : students)
	        e.writeData(out);
	}


	private static Student[] readData(Scanner in) {
		// TODO Auto-generated method stub
		int n = in.nextInt();
	    in.nextLine(); // consume newline

	    Student[] students = new Student[n];
	    for (int i = 0; i < n; i++)
	    {
	    	students[i] = new Student();
	    	students[i].readData(in);
	    }
	    return students;
	}

运行结果:

  • 4.2 生成的文件有多大?分析该文件大小?将该文件大小和题目1生成的文件对比是大了还是小了,为什么?

    答:将该文件大小和题目1生成的文件对比是大了。因为使用UTF-8编码存储文件,汉字所占字节数较大。

  • 4.3 使用wxMEdit的16进制模式(或者其他文本编辑器的16进制模式)打开student.data,分析数据在文件中是如何存储的。

  • 4.4 使用ObjectInputStream(读), ObjectOutputStream(写)读写学生。(截图关键代码,出现学号) //参考ObjectStreamTest目录。

//201521123044
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.txt"));
out.wirteObject(student);
out.close();
objectInputStream in = new objectInputStream(new FileOutputStream("student.txt"));
Student[] new Student = (Student[])in.readOject();
in.close;
for(Student e :new Student)
	System.out.println(e);

5.Scanner基本概念组装对象

编写public static List<Student> readStudents(String fileName)从fileName指定的文本文件中读取所有学生,并将其放入到一个List中。应该使用那些IO相关的类?说说你的选择理由。
需要用到:
FileInputStream:从文件中读
BufferedInputStream:以缓冲方式从文件流中读(速度更快)
FileInputStream:因为要读UTF-8格式的文件
运行结果:

6.选做:RandomAccessFile

  • 6.1 使用RandomAccessFile实现题目1.1。(截图关键代码,出现学号)

  • 6.2 分析文件大小

7.文件操作

编写一个程序,可以根据指定目录和文件名,搜索该目录及子目录下的所有文件,如果没有找到指定文件名,则显示无匹配,否则将所有找到的文件名与文件夹名显示出来。

  • 7.1 编写public static void findFile(String path,String filename)函数,以path指定的路径为根目录,在其目录与子目录下查找所有和filename相同的文件名,一旦找到就马上输出到控制台。(截图关键代码,出现学号)
//201521123044
	public static void findFile(String path,String filename){
		File pathName = new File(path);
		String[] fileNames = pathName.list();
		for (String string : fileNames) {
			File f = new File(pathName.getAbsolutePath(),string);
			if (string.equals(filename)) {
				System.out.println(f.getAbsolutePath());
			}
			if (f.isDirectory()) {
				findFile(f.getAbsolutePath(),filename);
			}
		}
	}
	public static void main(String[] args) {
		findFile("F:\\workspace","Stream.txt");
}

运行结果:

  • 7.2 加分点:使用队列、使用图形界面、使用Java NIO.2完成(任选1)

  • 7.3 选做:实现删掉指定目录及其子目录下的所有空文件夹。
    参考代码:FindDirectories.java
    参考:本题具体要求见流与文件实验任务书-题目2

  • 7.4 选做:将指定目录及子目录下的所有.java文件,转化成UTF-8编码格式,并测试。
    参考资料:判断文件的编码格式

3.1. 码云代码提交记录

题目集:多线程(4-4到4-10)
截图多线程PTA提交列表

posted @ 2017-05-13 20:01  Min21  阅读(416)  评论(1编辑  收藏  举报