java答案第六章.docx

上传人:b****6 文档编号:7761168 上传时间:2023-01-26 格式:DOCX 页数:24 大小:227.90KB
下载 相关 举报
java答案第六章.docx_第1页
第1页 / 共24页
java答案第六章.docx_第2页
第2页 / 共24页
java答案第六章.docx_第3页
第3页 / 共24页
java答案第六章.docx_第4页
第4页 / 共24页
java答案第六章.docx_第5页
第5页 / 共24页
点击查看更多>>
下载资源
资源描述

java答案第六章.docx

《java答案第六章.docx》由会员分享,可在线阅读,更多相关《java答案第六章.docx(24页珍藏版)》请在冰豆网上搜索。

java答案第六章.docx

java答案第六章

Java语言程序设计

第六章课后习题答案

1.将本章例6-1至6-18中出现的文件的构造方法均改为使用File类对象作为参数实现。

个人理解:

File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。

注意:

是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。

importjava.io.*;

publicclasstest6_2{

publicstaticvoidmain(String[]args)throwsIOException{

StringfileName="D:

\\Hello.txt";

Filewriter=newFile(fileName);

writer.createNewFile();

BufferedWriterinput=newBufferedWriter(newFileWriter(writer));

input.write("Hello!

\n");

input.write("thisismyfirsttextfile,\n");

input.write("你还好吗?

\n");

input.close();

}

}

运行结果:

(电脑系统问题,没法换行,所以一般使用BuffereWriter中newLine()实现换行)

 

2.模仿文本文件复制的例题,编写对二进制文件进行复制的程序.

//CopyMaker类

importjava.io.*;

classCopyMaker{

StringsourceName,destName;

BufferedInputStreamsource;

BufferedOutputStreamdest;

intline;

//打开源文件和目标文件,无异常返回true

privatebooleanopenFiles(){

try{

source=newBufferedInputStream(newFileInputStream(sourceName));

}

catch(IOExceptioniox){

System.out.println("Problemopening"+sourceName);

returnfalse;

}

try{

dest=newBufferedOutputStream(newFileOutputStream(destName));

}

catch(IOExceptioniox)

{

System.out.println("Problemopening"+destName);

returnfalse;

}

returntrue;

}

//复制文件

privatebooleancopyFiles(){

try{

line=source.read();

while(line!

=-1){

dest.write(line);

line=source.read();

}

}

catch(IOExceptioniox){

System.out.println("Problemreadingorwriting");

returnfalse;

}

returntrue;

}

//关闭源文件和目标文件

privatebooleancloseFiles(){

booleanretVal=true;

try{source.close();}

catch(IOExceptioniox){

System.out.println("Problemclosing"+sourceName);

retVal=false;

}

try{dest.close();}

catch(IOExceptioniox){

System.out.println("Problemclosing"+destName);

retVal=false;

}

returnretVal;

}

//执行复制

publicbooleancopy(Stringsrc,Stringdst){

sourceName=src;

destName=dst;

returnopenFiles()&©Files()&&closeFiles();

}

}

 

//test6_2

publicclasstest6_2

{

publicstaticvoidmain(String[]args){

Strings1="lin.txt",s2="newlin.txt";

if(newCopyMaker().copy(s1,s2))

System.out.print("复制成功");

else

System.out.print("复制失败");

}

}

运行前的两个文本:

lin.txt和newlin.txt(为空)

运行后:

3.创建一存储若干随机整数的文本文件,文件名、整数的个数及范围均由键盘输入。

//memory存储类

 

importjava.io.*;

importjava.util.Random;

publicclassmemory{

privateStringname;

privateintcount;

privateintMax;

privateintMin;

publicmemory(Stringn,intc,intmin,intmax){

this.name=n;

this.count=c;

this.Min=min;

this.Max=max;

}

publicvoidstartmemory(){

try{

FileWriterout=newFileWriter(name);

intlimit=Max-Min;

Randomrandom=newRandom();

for(inti=1;i<=count;i++){

intnumber=Min+random.nextInt(limit);

System.out.print(number);

System.out.print("");

out.write(number+"");

}

out.close();

}catch(IOExceptioniox){

System.out.println("方法startmemory()有问题");

}

}

}

//test6_3

importjava.io.*;

importjava.util.Scanner;

publicclasstest6_3{

publicstaticvoidmain(String[]args)throwsIOException{

//BufferedReader

StringfileName;

intcount,min,max;

Scannerin=newScanner(System.in);

System.out.println("输入要存储的文件名");

fileName=in.next();

System.out.println("输入随机数个数");

count=in.nextInt();

System.out.println("输入随机数最小值");

min=in.nextInt();

System.out.println("输入随机数最大值");

max=in.nextInt();

memoryM=newmemory(fileName,count,min,max);

M.startmemory();

}

}

}

运行结果:

naruto文件存储二进制数:

4.分别使用FileWriter和BufferedWriter往文件中写入10万个随机数,比较用时的多少。

//FileWriter方法

importjava.io.*;

publicclassfileWriter{

publicstaticvoidmain(String[]args)throwsIOException{

longtime=System.currentTimeMillis();//当前时间

FileWriterfilewriter=newFileWriter("filewriter.txt");

intnumber;

for(inti=1;i<=100000;i++){

number=(int)(Math.random()*10000);

filewriter.write(number+"");

}

filewriter.close();

time=System.currentTimeMillis()-time;//时间差

System.out.println("用时为:

"+time+"微秒.");

}

}

运行结果:

//BufferedWriter方法

importjava.io.*;

publicclassbufferedWriter{

publicstaticvoidmain(String[]args)throwsIOException{

longtime=System.currentTimeMillis();//当前时间

BufferedWriterfilewriter=newBufferedWriter(newFileWriter("filewriter.txt"));

intnumber;

for(inti=1;i<=100000;i++){

number=(int)(Math.random()*10000);

filewriter.write(number+"");

}

filewriter.close();

time=System.currentTimeMillis()-time;//时间差

System.out.println("用时为:

"+time+"微秒.");

}

}

运行结果:

有用时可知:

BufferedWriter比FileWriter写入的速度快,当需要写入大量内容,前者效率高。

5.生成一html文件,使其能显示2的幂次(0~9)的表格如下:

Powerof2

Value

0

1

1

2

//test6_5类

importjava.io.*;

publicclasstest6_5{

publicstaticvoidmain(String[]args)throwsIOException{

BufferedWriterfuck=newBufferedWriter(newFileWriter("6_5.html"));

fuck.write("");

fuck.newLine();

fuck.write("Powerof2Value");

for(inti=0;i<=9;i++){

fuck.write(""+i+""+Math.pow(i,2)+"");

}

fuck.write("");

fuck.newLine();

fuck.close();

}

}

运行结果:

6.用记事本程序创建一篇包含几十个英语单词的小文章,要求从屏幕输出每一个单词。

//test6_6

importjava.io.*;

publicclasstest6_6{

publicstaticvoidmain(String[]args)throwsIOException{

FileReaderfr=newFileReader("naruto.txt");

ints;

while((s=fr.read())!

=-1){

if(s>='a'&&s<='z'||s>='A'&&s<='Z')

System.out.print((char)s);

else

System.out.print("\n");

}

fr.close();

}

}

运行结果:

7.从键盘敲入一系列字母,将其存储到文件中,对其进行升序排序后,存储到另一个文件,并显示在屏幕上。

//test6_7

importjava.io.*;

importjava.util.Scanner;

publicclasstest6_7{

//将字符串存入文件

publicstaticvoidWriteToFile(Strings,StringfileName){

try{

FileWriterwriter=newFileWriter(fileName);

writer.write(s);

writer.close();

}catch(IOExceptioniox){

System.out.println("写入字符串s到文件时出错!

");

}

}

//将字符串从文件中读取出来

publicstaticStringReadFromFile(StringfileName){

Strings=newString();

try{

BufferedReaderin=newBufferedReader(newFileReader(fileName));

s=in.readLine();

}catch(IOExceptionio){

System.out.println("从文件中读出字符串时出错!

");

}

returns;

}

//将字符串排序,然后返回字符串

publicstaticStringsort(Strings){

char[]c=s.toCharArray();//将字符串转换成字符数组

chartemp;

for(inti=0;i

for(intj=i+1;j

if(c[i]>c[j])

{

temp=c[i];

c[i]=c[j];

c[j]=temp;

}

s=newString(c);//注意不能用c.toString

returns;

}

publicstaticvoidmain(Stringargs[]){

Scannerin=newScanner(System.in);

Strings=in.next();//从键盘输入一组字符

WriteToFile(s,"D:

\\naruto.txt");//将字符串保存到D:

\naruto.txt

s=null;//将s清空,下面好读取,不然无法辨别s是读取到数据还是原来的数据

s=ReadFromFile("D:

\\naruto.txt");//从文件D:

\naruto.txt读出字符串

s=sort(s);//将s进行排序

WriteToFile(s,"D:

\\newnaruto.txt");//将排序后的内容保存到另一文件D:

\newnaruto.txt

System.out.println(s);

}

}

运行结果:

文件D:

\\naruto.txt和D:

\\newnaruto.txt中内容:

8.创建一个学生类(包括姓名、年龄、班级、密码),创建若干该类的对象并保存在文件中(密码不保存),从文件读取对象后显示在屏幕上。

//Student类

importjava.io.Serializable;

classStudentimplementsSerializable{

Stringname;

intage;

intgrade;

transientStringsecret;

publicStudent(Stringname,intage,intgrade,Stringsecret){

this.name=name;

this.age=age;

this.grade=grade;

this.secret=secret;

}

}

//test6_8

importjava.io.*;

publicclasstset6_8{

publicstaticvoidmain(String[]args)throwsIOException,ClassNotFoundException{

Studentstudent[]={

newStudent("苍井空",19,101,"changjingkong"),

newStudent("吉沢明",19,103,"jizeming"),

newStudent("武藤兰",20,104,"wutenglan"),

newStudent("我爱女优",21,105,"woainvyou")};

//创建输出

ObjectOutputStreamoos=newObjectOutputStream(

newFileOutputStream("naruto.dat"));

for(inti=0;i

oos.writeObject(student[i]);

oos.close();

//将对象数组student全部清空,后边你会明白的。

for(inti=0;i

student[i]=null;

//创建输入

ObjectInputStreamois=newObjectInputStream(

newFileInputStream("naruto.dat"));

for(inti=0;i

student[i]=(Student)ois.readObject();//重新从文件中读入,之前的清空就因为此读入。

注意,读入要强制转化为学生类

ois.close();

//显示信息

for(inti=0;i

if(i==student.length-1){

System.out.println("我的名字:

"+student[i].name);

System.out.println("我的年龄:

"+student[i].age);

System.out.println("我的班级:

"+student[i].grade);

System.out.println("我的密码:

"+student[i].secret);

System.out.println();

}

else{

System.out.println("第"+(i+1)+"个女学生名字:

"+student[i].name);

System.out.println("第"+(i+1)+"个女学生年龄:

"+student[i].age);

System.out.println("第"+(i+1)+"个女学生班级:

"+student[i].grade);

System.out.println("第"+(i+1)+"个女学生密码:

"+student[i].secret);

System.out.println();

}

}

}

}

9.对例6—14中的压缩程序段进行修改,是压缩流经过缓冲类。

比较两种方法在对大的文件进行压缩时的效率。

//没经过缓冲类,使用FileInputStream类

importjava.io.*;

importjava.util.zip.*;

publicclasstest6_9f{

publicstaticvoidmain(String[]args)throwsIOException{

longtime=System.currentTimeMillis();

FileInputStreamin=newFileInputStream("naruto.txt");

GZIPOutputStreamout=newGZIPOutputStream(

newFileOutputStream("test.gz"));

System.out.println("Writingcompressingfilefromnaruto.txttotest.gz");

intc;

while((c=in.read())!

=-1)out.write(c);//写压缩文件

in.close();

out.close();

System.out.println("Readingfileformtest.gztomonitor");

BufferedReaderin2=newBufferedReader(

newInputStreamReader(

newGZIPInputStream(

newFileInputStream("test.gz"))));

Strings;

while((s=in2.readLine())!

=null)System.out.println(s);

in2.clos

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 小学教育 > 语文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1