Java语言程序设计(郑莉)第六章课后习题答案 下载本文

内容发布更新时间 : 2024/5/16 2:48:24星期一 下面是文章的全部内容请认真阅读。

Java语言程序设计 第六章课后习题答案

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

个人理解:File类只能对整文件性质进行处理,而没法通过自己直接使用file.Read()或者是file.write()类似方法对文件内容进行写或者读取。注意:是直接;下面只提供一个例2变化,其他的你自己做,10几道啊,出这题的人真他妈有病。

import java.io.*; public class test6_2{ }

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

public static void main(String[] args) throws IOException {

String fileName = \; File writer=new File(fileName); writer.createNewFile();

BufferedWriter input = new BufferedWriter(new input.write(\);

input.write(\); input.write(\你还好吗?\\n\); input.close(); }

FileWriter(writer));

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

// CopyMaker类

import java.io.*; class CopyMaker {

String sourceName, destName; BufferedInputStream source; BufferedOutputStream dest; int line;

//打开源文件和目标文件,无异常返回true private boolean openFiles() {

try {

source = new BufferedInputStream(new FileInputStream( sourceName ));

}

catch ( IOException iox ) {

System.out.println(\ + sourceName ); return false; } try {

dest = new BufferedOutputStream(new FileOutputStream( destName )); }

catch ( IOException iox ) {

System.out.println(\ + destName ); return false; }

return true; }

//复制文件

private boolean copyFiles() { try {

line = source.read(); while ( line != -1 ) {

dest.write(line); line = source.read(); } }

catch ( IOException iox ) {

System.out.println(\ ); return false; }

return true; }

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

private boolean closeFiles() { boolean retVal=true; try { source.close(); } catch ( IOException iox ) {

System.out.println(\ + sourceName ); retVal = false; }

try { dest.close(); }

catch ( IOException iox ) {

System.out.println(\ + destName ); retVal = false; }

return retVal; }

//执行复制

public boolean copy(String src, String dst ) { sourceName = src ; destName = dst ;

return openFiles() && copyFiles() && closeFiles(); } }

//test6_2

public class test6_2 {

public static void main ( String[] args ) {

String s1=\,s2=\;

if(new CopyMaker().copy(s1, s2)) System.out.print(\复制成功\); else

System.out.print(\复制失败\); } }

运行前的两个文本:lin.txt和newlin.txt(为空)

运行后: