您好,欢迎访问三七文档
集美大学诚毅学院实验报告课程名称:java班级:1371实验成绩:指导教师:姓名:方XX实验项目名称:学号:201342051022上机实践日期:实验项目编号:实验四上机实践时间:一、实验步骤和调试过程1、数字存取:通过随机数函数产生50个正整数,逐个将这些数写入文件file.dat中;然后读出这些数,在内存中对它们进行排序,再将排序后的数据逐个写入file.out文件中。packagefds;importjava.io.*;importjava.util.*;publicclasstext{publicstaticvoidmain(String[]args)throwsIOException{Filea=newFile(f:/111.txt);Fileb=newFile(f:/222.txt);a.createNewFile();b.createNewFile();BufferedReaderin=null;BufferedWriterout1=null,out2=null;Randomrand=newRandom(10);int[]arr=newint[50];try{out1=newBufferedWriter(newFileWriter(a));out2=newBufferedWriter(newFileWriter(b));for(inti=0;iarr.length;i++){out1.write(String.valueOf(rand.nextInt(20)));out1.write();if(i%10==9)out1.newLine();}out1.close();Scannersc=newScanner(a);for(inti=0;sc.hasNextInt();i++){arr[i]=sc.nextInt();}Arrays.sort(arr);for(inti=0;iarr.length;i++){out2.write(String.valueOf(arr[i]));out2.write();if(i%10==9)out2.newLine();}}finally{if(in!=null){in.close();}if(out2!=null){out2.close();}}}}2、文件内容加行号:给定一个文件,通过文件读写,给文件内容加行号。packagefds;importjava.io.*;importjava.util.*;publicclasstext{publicstaticvoidmain(String[]args)throwsIOException{ListStringlist=newArrayListString();try{Filef=newFile(f:/222.txt);Scannersc=newScanner(f);intk=0;while(sc.hasNextLine()){list.add(++k++sc.nextLine());}BufferedWriterout=newBufferedWriter(newFileWriter(f));for(inti=0;ilist.size();i++)out.write(list.get(i)+\r\n);out.close();System.out.println(操作完成!);}finally{}}}3、学生对象操作:设计学生类,把学生对象存储进文件,并能再从文件中读取。packagefds;importjava.io.*;publicclasstext{publicstaticvoidmain(String[]args)throwsIOException,ClassNotFoundException{Stu[]st={newStu(大夫,2,男),newStu(帷幕,3,女),newStu(晚上人,4,男)};Filefile=newFile(d:/students.txt);file.createNewFile();ObjectOutputStreamout=null;try{out=newObjectOutputStream(newFileOutputStream(file));for(inti=0;ist.length;i++){out.writeObject(st[i]);}}finally{out.close();}ObjectInputStreamin=null;try{in=newObjectInputStream(newFileInputStream(file));Stu[]st2={null,null,null};for(inti=0;ist2.length;i++){st2[i]=(Stu)in.readObject();System.out.println(st2[i]);}}finally{in.close();}}}classStuimplementsSerializable{Stringstu_name;intstu_no;Stringstu_age;publicStu(Stringstu_name,intstu_no,Stringstu_age){this.stu_name=stu_name;this.stu_no=stu_no;this.stu_age=stu_age;}publicStringtoString(){System.out.println(姓名学号性别);returnstu_name+stu_no+stu_age;}}
本文标题:实验四_JAVA
链接地址:https://www.777doc.com/doc-6042481 .html