《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(\, true)); ) {
for (int i = 0; i < 100; i++)
output.format(\, (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(\, true)); ) {
for (int i = 0; i < 100; i++)
output.writeInt((int)(Math.random() * 100000)); }
System.out.println(\); } }
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(\)); ) {
int total = 0;
while (dis.available() > 0) { int temp = dis.readInt(); total += temp; count++;
System.out.print(temp + \); }
System.out.println(\ + count); System.out.println(\ + total); }
catch (FileNotFoundException ex) { System.out.println(\); }
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] + \ + input1.available() + \bytes\);
System.out.println(args[1] + \ + 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(\)); ) {
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(\)); ) {
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));