-
Notifications
You must be signed in to change notification settings - Fork 1
/
chapter11.java
825 lines (654 loc) · 18.8 KB
/
chapter11.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
// Read an array of bytes from the keyboard.
import java.io.*;
class ReadBytes {
public static void main(String[] args)
throws IOException {
byte[] data = new byte[10];
System.out.println("Enter some characters.");
int numRead = System.in.read(data);
System.out.print("You entered: ");
for(int i=0; i < numRead; i++)
System.out.print((char) data[i]);
}
}
// -----------------------------------------
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String[] args) {
int b;
b = 'X';
System.out.write(b);
System.out.write('\n');
}
}
// -----------------------------------------
/* Display a text file.
To use this program, specify the name
of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.
java ShowFile TEST.TXT
*/
import java.io.*;
class ShowFile {
public static void main(String[] args)
{
int i;
FileInputStream fin;
// First make sure that a file has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile File");
return;
}
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException exc) {
System.out.println("File Not Found");
return;
}
try {
// read bytes until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException exc) {
System.out.println("Error reading file.");
}
try {
fin.close();
} catch(IOException exc) {
System.out.println("Error closing file.");
}
}
}
// -----------------------------------------
/* This variation wraps the code that opens and
accesses the file within a single try block.
The file is closed by the finally block.
*/
import java.io.*;
class ShowFile {
public static void main(String[] args)
{
int i;
FileInputStream fin = null;
// First, confirm that a file name has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// The following code opens a file, reads characters until EOF
// is encountered, and then closes the file via a finally block.
try {
fin = new FileInputStream(args[0]);
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(FileNotFoundException exc) {
System.out.println("File Not Found.");
} catch(IOException exc) {
System.out.println("An I/O Error Occurred");
} finally {
// Close file in all cases.
try {
if(fin != null) fin.close();
} catch(IOException exc) {
System.out.println("Error Closing File");
}
}
}
}
// -----------------------------------------
/* Copy a text file.
To use this program, specify the name
of the source file and the destination file.
For example, to copy a file called FIRST.TXT
to a file called SECOND.TXT, use the following
command line.
java CopyFile FIRST.TXT SECOND.TXT
*/
import java.io.*;
class CopyFile {
public static void main(String[] args)
{
int i;
FileInputStream fin = null;
FileOutputStream fout = null;
// First, make sure that both files has been specified.
if(args.length != 2) {
System.out.println("Usage: CopyFile from to");
return;
}
// Copy a File.
try {
// Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
} finally {
try {
if(fin != null) fin.close();
} catch(IOException exc) {
System.out.println("Error Closing Input File");
}
try {
if(fout != null) fout.close();
} catch(IOException exc) {
System.out.println("Error Closing Output File");
}
}
}
}
// -----------------------------------------
/* This version of the ShowFile program uses a try-with-resources
statement to automatically close a file when it is no longer needed.
Note: This code requires JDK 7 or later.
*/
import java.io.*;
class ShowFile {
public static void main(String[] args)
{
int i;
// First, make sure that a file name has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// The following code uses try-with-resources to open a file
// and then automatically close it when the try block is left.
try(FileInputStream fin = new FileInputStream(args[0])) {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
// -----------------------------------------
/* A version of CopyFile that uses try-with-resources.
It demonstrates two resources (in this case files) being
managed by a single try statement.
Note: This code requires JDK 7 or later.
*/
import java.io.*;
class CopyFile {
public static void main(String[] args)
{
int i;
// First, confirm that both files have been specified.
if(args.length != 2) {
System.out.println("Usage: CopyFile from to");
return;
}
// Open and manage two files via the try statement.
try (FileInputStream fin = new FileInputStream(args[0]);
FileOutputStream fout = new FileOutputStream(args[1]))
{
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
// -----------------------------------------
// Write and then read back binary data.
// This code requires JDK 7 or later.
import java.io.*;
class RWData {
public static void main(String[] args)
{
int i = 10;
double d = 1023.56;
boolean b = true;
// Write some values.
try (DataOutputStream dataOut =
new DataOutputStream(new FileOutputStream("testdata")))
{
System.out.println("Writing " + i);
dataOut.writeInt(i);
System.out.println("Writing " + d);
dataOut.writeDouble(d);
System.out.println("Writing " + b);
dataOut.writeBoolean(b);
System.out.println("Writing " + 12.2 * 7.4);
dataOut.writeDouble(12.2 * 7.4);
}
catch(IOException exc) {
System.out.println("Write error.");
return;
}
System.out.println();
// Now, read them back.
try (DataInputStream dataIn =
new DataInputStream(new FileInputStream("testdata")))
{
i = dataIn.readInt();
System.out.println("Reading " + i);
d = dataIn.readDouble();
System.out.println("Reading " + d);
b = dataIn.readBoolean();
System.out.println("Reading " + b);
d = dataIn.readDouble();
System.out.println("Reading " + d);
}
catch(IOException exc) {
System.out.println("Read error.");
}
}
}
// -----------------------------------------
/*
Try This 11-1
Compare two files.
To use this program, specify the names
of the files to be compared on the command line.
java CompFiles FIRST.TXT SECOND.TXT
This code requires JDK 7 or later.
*/
import java.io.*;
class CompFiles {
public static void main(String[] args)
{
int i=0, j=0;
// First make sure that both files have been specified.
if(args.length !=2 ) {
System.out.println("Usage: CompFiles f1 f2");
return;
}
// Compare the files.
try (FileInputStream f1 = new FileInputStream(args[0]);
FileInputStream f2 = new FileInputStream(args[1]))
{
// Check the contents of each file.
do {
i = f1.read();
j = f2.read();
if(i != j) break;
} while(i != -1 && j != -1);
if(i != j)
System.out.println("Files differ.");
else
System.out.println("Files are the same.");
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
// -----------------------------------------
// Demonstrate random access files.
// This code requires JDK 7 or later.
import java.io.*;
class RandomAccessDemo {
public static void main(String[] args)
{
double[] data = { 19.4, 10.1, 123.54, 33.0, 87.9, 74.25 };
double d;
// Open and use a random access file.
try (RandomAccessFile raf = new RandomAccessFile("random.dat", "rw"))
{
// Write values to the file.
for(int i=0; i < data.length; i++) {
raf.writeDouble(data[i]);
}
// Now, read back specific values
raf.seek(0); // seek to first double
d = raf.readDouble();
System.out.println("First value is " + d);
raf.seek(8); // seek to second double
d = raf.readDouble();
System.out.println("Second value is " + d);
raf.seek(8 * 3); // seek to fourth double
d = raf.readDouble();
System.out.println("Fourth value is " + d);
System.out.println();
// Now, read every other value.
System.out.println("Here is every other value: ");
for(int i=0; i < data.length; i+=2) {
raf.seek(8 * i); // seek to ith double
d = raf.readDouble();
System.out.print(d + " ");
}
}
catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
// -----------------------------------------
// Use a BufferedReader to read characters from the console.
import java.io.*;
class ReadChars {
public static void main(String[] args)
throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, period to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != '.');
}
}
// -----------------------------------------
// Read a string from console using a BufferedReader.
import java.io.*;
class ReadLines {
public static void main(String[] args)
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
// -----------------------------------------
// Demonstrate PrintWriter.
import java.io.*;
public class PrintWriterDemo {
public static void main(String[] args) {
PrintWriter pw = new PrintWriter(System.out, true);
int i = 10;
double d = 123.65;
pw.println("Using a PrintWriter.");
pw.println(i);
pw.println(d);
pw.println(i + " + " + d + " is " + (i+d));
}
}
// -----------------------------------------
// A simple key-to-disk utility that demonstrates a FileWriter.
// This code requires JDK 7 or later.
import java.io.*;
class KtoD {
public static void main(String[] args)
{
String str;
BufferedReader br =
new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter text ('stop' to quit).");
try (FileWriter fw = new FileWriter("test.txt"))
{
do {
System.out.print(": ");
str = br.readLine();
if(str.compareTo("stop") == 0) break;
str = str + "\r\n"; // add newline
fw.write(str);
} while(str.compareTo("stop") != 0);
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
// -----------------------------------------
// A simple disk-to-screen utility that demonstrates a FileReader.
// This code requires JDK 7 or later.
import java.io.*;
class DtoS {
public static void main(String[] args) {
String s;
// Create and use a FileReader wrapped in a BufferedReader.
try (BufferedReader br = new BufferedReader(new FileReader("test.txt")))
{
while((s = br.readLine()) != null) {
System.out.println(s);
}
} catch(IOException exc) {
System.out.println("I/O Error: " + exc);
}
}
}
// -----------------------------------------
// Obtain information about a file.
import java.io.*;
class FileDemo {
public static void main(String[] args) {
File myFile = new File("/javafiles/MyClass.java");
System.out.println("File Name: " + myFile.getName());
System.out.println("Path: " + myFile.getPath());
System.out.println("Abs Path: " + myFile.getAbsolutePath());
System.out.println("Parent: " + myFile.getParent());
System.out.println(myFile.exists() ? "exists" : "does not exist");
System.out.println(myFile.isHidden() ? "is hidden" :
"is not hidden");
System.out.println(myFile.canWrite() ? "is writeable" :
"is not writeable");
System.out.println(myFile.canRead() ? "is readable" :
"is not readable");
System.out.println("is " + (myFile.isDirectory() ? "" :
"not" + " a directory"));
System.out.println(myFile.isFile() ? "is normal file" :
"might be a named pipe");
System.out.println(myFile.isAbsolute() ? "is absolute" :
"is not absolute");
System.out.println("File size: " + myFile.length() + " Bytes");
}
}
// -----------------------------------------
// Using directories.
import java.io.*;
class DirList {
public static void main(String[] args) {
String dirname = "/javafiles";
File myDir = new File(dirname);
if (myDir.isDirectory()) {
System.out.println("Directory of " + dirname);
String[] s = myDir.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
// -----------------------------------------
import java.io.*;
public class FilterExt implements FilenameFilter {
String ext;
public FilterExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
// -----------------------------------------
// Directory of .java files.
import java.io.*;
class DirListFiltered {
public static void main(String[] args) {
FilenameFilter only = new FilterExt("java");
String dirname = "/javafiles";
File myDir = new File(dirname);
if (myDir.isDirectory()) {
System.out.println("Java source files in " + dirname);
String[] s = myDir.list(only);
for (int i=0; i < s.length; i++) {
System.out.println(s[i]);
}
}
}
}
// -----------------------------------------
// Show the free space on the current drive partition.
import java.io.*;
class FreeSpace {
public static void main(String[] args) {
File myFile = new File("\\");
System.out.println("Free Space: " + myFile.getFreeSpace());
}
}
// -----------------------------------------
// This program averages a list of numbers entered by the user.
import java.io.*;
class AvgNums {
public static void main(String[] args)
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
String str;
int n;
double sum = 0.0;
double avg, t;
System.out.print("How many numbers will you enter: ");
str = br.readLine();
try {
n = Integer.parseInt(str);
}
catch(NumberFormatException exc) {
System.out.println("Invalid format");
n = 0;
}
System.out.println("Enter " + n + " values.");
for(int i=0; i < n ; i++) {
System.out.print(": ");
str = br.readLine();
try {
t = Double.parseDouble(str);
} catch(NumberFormatException exc) {
System.out.println("Invalid format");
t = 0.0;
}
sum += t;
}
avg = sum / n;
System.out.println("Average is " + avg);
}
}
// -----------------------------------------
Contents of helpfile.txt:
#if
if(condition) statement;
else statement;
#switch
switch(expression) {
case constant:
statement sequence
break;
// ...
}
#for
for(init; condition; iteration) statement;
#while
while(condition) statement;
#do
do {
statement;
} while (condition);
#break
break; or break label;
#continue
continue; or continue label;
// -----------------------------------------
/*
Try This 11-2
A help program that uses a disk file
to store help information.
This code requires JDK 7 or later.
*/
import java.io.*;
/* The Help class opens a help file,
searches for a topic, and then displays
the information associated with that topic.
Notice that it handles all I/O exceptions
itself, avoiding the need for calling
code to do so. */
class Help {
String helpfile; // name of help file
Help(String fname) {
helpfile = fname;
}
// Display help on a topic.
boolean helpOn(String what) {
int ch;
String topic, info;
// Open the help file.
try (BufferedReader helpRdr =
new BufferedReader(new FileReader(helpfile)))
{
do {
// read characters until a # is found
ch = helpRdr.read();
// now, see if topics match
if(ch == '#') {
topic = helpRdr.readLine();
topic = topic.trim(); // remove leading and trailing
// whitespace
if(what.compareTo(topic) == 0) { // found topic
do {
info = helpRdr.readLine();
if(info != null) System.out.println(info);
} while((info != null) &&
(info.trim().compareTo("") != 0));
return true;
}
}
} while(ch != -1);
}
catch(IOException exc) {
System.out.println("Error accessing help file.");
return false;
}
return false; // topic not found
}
// Get a Help topic.
String getSelection() {
String topic = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter topic: ");
try {
topic = br.readLine();
}
catch(IOException exc) {
System.out.println("Error reading console.");
}
return topic;
}
}
// Demonstrate the file-based Help system.
class FileHelp {
public static void main(String[] args) {
Help hlpobj = new Help("helpfile.txt");
String topic;
System.out.println("Try the help system. " +
"Enter 'stop' to end.");
do {
topic = hlpobj.getSelection();
if(!hlpobj.helpOn(topic))
System.out.println("Topic not found.\n");
} while(topic.compareTo("stop") != 0);
}
}