Java Reference
In-Depth Information
39
merge((numberOfSegments +
1
) /
2
, segmentSize *
2
,
merge recursively
40
f3, f1, f2, targetfile);
41 }
42
else
{
// Rename f1 as the final sorted file
43 File sortedFile =
new
File(targetfile);
44
final sorted file
if
(sortedFile.exists()) sortedFile.delete();
45
new
File(f1).renameTo(sortedFile);
46 }
47 }
48
49
private static void
mergeOneStep(
int
numberOfSegments,
50
int
segmentSize, String f1, String f2, String f3)
51
throws
Exception {
52 DataInputStream f1Input =
new
DataInputStream(
53
new
BufferedInputStream(
new
FileInputStream(f1), BUFFER_SIZE));
54 DataOutputStream f2Output =
new
DataOutputStream(
55
new
BufferedOutputStream(
new
FileOutputStream(f2), BUFFER_SIZE));
56
57
// Copy half number of segments from f1.dat to f2.dat
58 copyHalfToF2(numberOfSegments, segmentSize, f1Input, f2Output);
59 f2Output.close();
60
61
// Merge remaining segments in f1 with segments in f2 into f3
62 DataInputStream f2Input =
new
DataInputStream(
63
new
BufferedInputStream(
new
FileInputStream(f2), BUFFER_SIZE));
64 DataOutputStream f3Output =
new
DataOutputStream(
65
new
BufferedOutputStream(
new
FileOutputStream(f3), BUFFER_SIZE));
66
67
input stream
f1Input
output stream
f2Output
copy half segments to
f2
close
f2Output
input stream
f2Input
output stream
f3Output
mergeSegments(numberOfSegments /
2
,
merge two segments
68
segmentSize, f1Input, f2Input, f3Output);
69
70 f1Input.close();
71 f2Input.close();
72 f3Output.close();
73 }
74
75
close streams
/** Copy first half number of segments from f1.dat to f2.dat */
76
private static void
copyHalfToF2(
int
numberOfSegments,
77
int
segmentSize, DataInputStream f1, DataOutputStream f2)
78
throws
Exception {
79
// Same as Listing 23.13, so omitted
80 }
81
82
/** Merge all segments */
83
private static void
mergeSegments(
int
numberOfSegments,
84
int
segmentSize, DataInputStream f1, DataInputStream f2,
85 DataOutputStream f3)
throws
Exception {
86
// Same as Listing 23.14, so omitted
87 }
88
89
/** Merges two segments */
90
private static void
mergeTwoSegments(
int
segmentSize,
91 DataInputStream f1, DataInputStream f2,
92 DataOutputStream f3)
throws
Exception {
93
// Same as Listing 23.15, so omitted
94 }
95
96
/** Display the first 100 numbers in the specified file */
97
public static void
displayFile(String filename) {
display file
98
try
{
Search WWH ::
Custom Search