《Java语言程序设计(基础篇)》(第10版 梁勇 著)第十七章练习题答案
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
《Java语言程序设计(基础篇)》(第10版梁勇著)
第十七章练习题答案
17.1
import java.io.*;
import java.util.*;
public class Exercise17_01 {
public static void main(String[] args) throws IOException {
try (
Formatter output =
new Formatter(new FileOutputStream("Exercise17_01.txt", true)); ) {
for (int i = 0; i < 100; i++)
output.format("%d", (int)(Math.random() * 100000));
}
}
}
17.2
import java.io.*;
public class Exercise17_02 {
public static void main(String[] args) throws IOException {
try (
DataOutputStream output =
new DataOutputStream(new FileOutputStream("Exercise17_02.dat", true));
) {
for (int i = 0; i < 100; i++)
output.writeInt((int)(Math.random() * 100000));
}
System.out.println("Done");
}
}
17.3
import java.io.*;
public class Exercise17_03 {
/** Main method */
public static void main(String[] args) {
// Read data
int count = 0;
try ( // Declare and create data input and output streams
DataInputStream dis =
new DataInputStream(new FileInputStream("Exercise17_03.dat"));
) {
int total = 0;
while (dis.available() > 0) {
int temp = dis.readInt();
total += temp;
count++;
System.out.print(temp + " ");
}
System.out.println("\nCount is " + count);
System.out.println("\nTotal is " + total);
}
catch (FileNotFoundException ex) {
System.out.println("File not found");
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
17.4
import java.io.*;
public class Exercise17_04 {
public static void main(String[] args) throws IOException {
try (
BufferedReader input = new BufferedReader(new FileReader(args[0])); DataOutputStream output = new DataOutputStream(new
FileOutputStream(args[1]));
) {
String line;
while ((line = input.readLine()) != null)
output.writeUTF(line);
}
try (
InputStream input1 = new FileInputStream(args[0]);
InputStream input2 = new FileInputStream(args[1]);
) {
System.out.println(args[0] + "'s size is " + input1.available() + " bytes");
System.out.println(args[1] + "'s size is " + input2.available() + " bytes");
}
}
}
17.5
import java.io.*;
public class Exercise17_05 {
public static void main(String[] args) throws IOException {
try (
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("Exercise17_05.dat"));
) {
output.writeObject(new int[]{1, 2, 3, 4, 5});
output.writeObject(new java.util.Date());
output.writeDouble(5.5);
}
}
}
17.6
import java.io.*;
public class Exercise17_06 {
public static void main(String[] args) throws IOException {
try (
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("Exercise17_06.dat"));
) {
output.writeObject(new Loan(2.5, 5, 1000));
output.writeObject(new Loan(3.5, 5, 2000));
output.writeObject(new Loan(4.5, 5, 3000));
output.writeObject(new Loan(5.5, 5, 4000));