Java2实用教程(第二版)程序代码——第二十章 输入输出流
1
//例子1
2
import java.io.*;
3
class Example20_1
4
{ public static void main(String args[])
5
{ File f1=new File("F:\\8000","Example20_1.java");
6
File f2=new File("F:\\8000");
7
System.out.println("文件Example20_1是可读的吗:"+f1.canRead());
8
System.out.println("文件Example20_1的长度:"+f1.length());
9
System.out.println("文件Example20_1的绝对路径:"+f1.getAbsolutePath());
10
System.out.println("F:\\8000:是目录吗?"+f2.isDirectory());
11
}
12
}
13![]()
14
//例子2
15
import java.io.*;
16
class FileAccept implements FilenameFilter
17
{ String str=null;
18
FileAccept(String s)
19
{ str="."+s;
20
}
21
public boolean accept(File dir,String name)
22
{ return name.endsWith(str);
23
}
24
}
25
public class Example20_2
26
{ public static void main(String args[])
27
{ File dir=new File("F:/8000");
28
FileAccept acceptCondition=new FileAccept("java");
29
String fileName[]=dir.list(acceptCondition);
30
for(int i=0;i<5;i++)
31
{ System.out.println(fileName[i]);
32
}
33
}
34
}
35![]()
36
//例子3
37
import java.io.*;import java.awt.*;import java.awt.event.*;
38
class Example20_3
39
{ public static void main(String args[])
40
{ int b;
41
TextArea text;
42
Frame window=new Frame();
43
byte tom[]=new byte[25];
44
window.setSize(100,100);text=new TextArea(10,16);
45
window.setVisible(true);window.add(text,BorderLayout.CENTER);
46
window.pack();
47
window.addWindowListener(new WindowAdapter()
48
{ public void windowClosing(WindowEvent e)
49
{ System.exit(0);
50
}
51
});
52
53
try{ File f=new File("F:\\8000","Example20_1.java");
54
FileInputStream readfile=new FileInputStream(f);
55
while((b=readfile.read(tom,0,25))!=-1)
56
{
57
String s=new String (tom,0,b);
58
System.out.println(s);
59
text.append(s);
60
}
61
readfile.close();
62
}
63
catch(IOException e)
64
{ System.out.println("File read Error");
65
}
66
}
67
}
68![]()
69
//例子4
70
import java.io.*;
71
class Example20_4
72
{ public static void main(String args[])
73
{ int b;
74
byte buffer[]=new byte[100];
75
try{ System.out.println("输入一行文本,并存入磁盘:");
76
b=System.in.read(buffer); //把从键盘敲入的字符存入buffer。
77
FileOutputStream writefile=new FileOutputStream("line.txt");
78
writefile.write(buffer,0,b); // 通过流把 buffer写入到文件line.txt。
79
}
80
catch(IOException e)
81
{ System.out.println("Error ");
82
}
83
}
84
}
85![]()
86
//例子5
87
import java.io.*;import java.awt.*;import java.awt.event.*;
88
class Example20_5
89
{ public static void main(String args[])
90
{ char a[]="今晚10点发起总攻".toCharArray();
91
int n=0,m=0;
92
try{ File f=new File("F:\\8000","secret.txt");
93
for(int i=0;i<a.length;i++)
94
{ a[i]=(char)(a[i]^'R');
95
}
96
FileWriter out=new FileWriter(f);
97
out.write(a,0,a.length);
98
out.close();
99
FileReader in=new FileReader(f);
100
int length=(int)f.length();
101
char tom[]=new char[length];
102
while((n=in.read(tom,0,length))!=-1)
103
{ String s=new String (tom,0,n);
104
m=n;
105
System.out.println("密文:"+s);
106
}
107
in.close();
108
for(int i=0;i<m;i++)
109
{ tom[i]=(char)(tom[i]^'R');
110
}
111
String 明文=new String(tom,0,m);
112
System.out.println("明文:"+明文);
113
}
114
catch(IOException e)
115
{ System.out.println("File read Error");
116
}
117
}
118
}
119![]()
120
//例子6
121
import java.io.*;
122
import java.awt.*;
123
import java.awt.event.*;
124
class EWindow extends Frame implements ActionListener
125
{ TextArea text;
126
Button buttonRead,buttonWrite;
127
BufferedReader bufferIn;
128
FileReader in;
129
BufferedWriter bufferOut;
130
FileWriter out;
131
EWindow()
132
{ super("流的读取");
133
text=new TextArea(10,10);text.setBackground(Color.cyan);
134
buttonRead =new Button("读取");
135
buttonRead.addActionListener(this);
136
buttonWrite =new Button("写出");
137
buttonWrite.addActionListener(this);
138
setLayout(new BorderLayout());
139
setSize(340,340);
140
setVisible(true);
141
add(text,BorderLayout.CENTER);
142
Panel pNorth=new Panel();
143
pNorth.add(buttonRead);pNorth.add(buttonWrite);
144
pNorth.validate();
145
add(BorderLayout.NORTH,pNorth);
146
addWindowListener(new WindowAdapter()
147
{ public void windowClosing(WindowEvent e)
148
{ System.exit(0);
149
}
150
});
151
}
152
public void actionPerformed(ActionEvent e)
153
{ String s;
154
if(e.getSource()==buttonRead)
155
{ try{ text.setText(null);
156
File f=new File("F:\\8000\\","E.java");
157
in=new FileReader(f);
158
bufferIn=new BufferedReader(in);
159
while((s=bufferIn.readLine())!=null)
160
{ text.append(s+'\n');
161
}
162
bufferIn.close();
163
in.close();
164
}
165
catch(IOException exp){System.out.println(exp);}
166
}
167
if(e.getSource()==buttonWrite)
168
{ try { File f=new File("F:\\8000\\","E.java");
169
FileWriter out=new FileWriter(f);
170
BufferedWriter bufferOut=new BufferedWriter(out);
171
bufferOut.write(text.getText(),0,(text.getText()).length());
172
bufferOut.flush();
173
bufferOut.close();
174
out.close();
175
}
176
catch(IOException exp){ System.out.println(exp);}
177
}
178
}
179
}
180
public class Example20_6
181
{ public static void main(String args[])
182
{ EWindow w=new EWindow();
183
w.validate();
184
}
185
}
186![]()
187
//例子7
188
import java.util.*;import java.io.*;
189
import java.awt.*;import java.awt.event.*;
190
class EWindow extends Frame implements ActionListener,ItemListener
191
{ String str[]=new String[7];String s;
192
FileReader file;
193
BufferedReader in;
194
Button start,next;
195
Checkbox box[];
196
TextField 题目,分数;
197
int score=0;
198
CheckboxGroup age=new CheckboxGroup();
199
EWindow()
200
{ super("英语单词学习");
201
分数=new TextField(10);题目=new TextField(70);
202
start=new Button("重新练习");start.addActionListener(this);
203
next=new Button("下一题目");next.addActionListener(this);
204
box=new Checkbox[4];
205
for(int i=0;i<=3;i++)
206
{ box[i]=new Checkbox("",false,age);
207
box[i].addItemListener(this);
208
}
209
try { file=new FileReader("English.txt");
210
in=new BufferedReader(file);
211
}
212
catch(IOException e){}
213
setBounds(100,100,400,320); setVisible(true);
214
setLayout(new GridLayout(4,1));
215
setBackground(Color.pink);
216
Panel p1=new Panel(),p2=new Panel(),
217
p3=new Panel() ,p4=new Panel(),p5=new Panel();
218
p1.add(new Label("题目:"));p1.add(题目);
219
p2.add(new Label("选择答案:"));
220
for(int i=0;i<=3;i++)
221
{ p2.add(box[i]);
222
}
223
p3.add(new Label("您的得分:"));p3.add(分数);
224
p4.add(start); p4.add(next);
225
add(p1); add(p2);add(p3); add(p4);
226
addWindowListener(new WindowAdapter()
227
{public void windowClosing(WindowEvent e)
228
{ System.exit(0);
229
}
230
});
231
reading();
232
}
233
public void reading()
234
{ int i=0;
235
try { s=in.readLine();
236
if(!(s.startsWith("endend")))
237
{ StringTokenizer tokenizer=new StringTokenizer(s,"#");
238
while(tokenizer.hasMoreTokens())
239
{ str[i]=tokenizer.nextToken();
240
i++;
241
}
242
题目.setText(str[0]);
243
for(int j=1;j<=4;j++)
244
{ box[j-1].setLabel(str[j]);
245
}
246
}
247
else if(s.startsWith("endend"))
248
{ 题目.setText("学习完毕");
249
for(int j=0;j<4;j++)
250
{ box[j].setLabel("end");
251
in.close();file.close();
252
}
253
}
254
}
255
catch(Exception exp){ 题目.setText("无试题文件") ; }
256
}
257
public void actionPerformed(ActionEvent event)
258
{ if(event.getSource()==start)
259
{ score=0;
260
分数.setText("得分: "+score);
261
try { file=new FileReader("English.txt");
262
in=new BufferedReader(file);
263
}
264
catch(IOException e){}
265
reading();
266
}
267
if(event.getSource()==next)
268
{ reading();
269
for(int j=0;j<4;j++)
270
{
271
box[j].setEnabled(true);
272
}
273
}
274
}
275
public void itemStateChanged(ItemEvent e)
276
{ for(int j=0;j<4;j++)
277
{ if(box[j].getLabel().equals(str[5])&&box[j].getState())
278
{ score++;
279
分数.setText("得分: "+score);
280
}
281
box[j].setEnabled(false);
282
}
283
}
284
}
285
public class Example20_7
286
{ public static void main(String args[])
287
{ EWindow w=new EWindow();
288
w.pack();
289
}
290
}
291![]()
292
//例子8
293
import java.awt.*;import java.io.*;
294
import java.awt.event.*;
295
public class Example20_8
296
{ public static void main(String args[])
297
{ FileWindows win=new FileWindows();
298
}
299
}
300
class FileWindows extends Frame implements ActionListener
301
{ FileDialog filedialog_save,filedialog_load;//声明2个文件对话筐
302
MenuBar menubar;
303
Menu menu;
304
MenuItem itemOpen,itemSave;
305
TextArea text;
306
BufferedReader in;
307
FileReader file_reader;
308
BufferedWriter out;
309
FileWriter tofile;
310
FileWindows()
311
{ super("带文件对话框的窗口");
312
setSize(260,270);
313
setVisible(true);
314
menubar=new MenuBar();
315
menu=new Menu("文件");
316
itemOpen=new MenuItem("打开文件");
317
itemSave=new MenuItem("保存文件");
318
itemOpen.addActionListener(this);
319
itemSave.addActionListener(this);
320
menu.add(itemOpen);
321
menu.add(itemSave);
322
menubar.add(menu);
323
setMenuBar(menubar);
324
filedialog_save=new FileDialog(this,"保存文件话框",FileDialog.SAVE);
325
filedialog_load=new FileDialog(this,"打开文件话框",FileDialog.LOAD);
326
filedialog_save.addWindowListener(new WindowAdapter()
327
{public void windowClosing(WindowEvent e)
328
{ filedialog_save.setVisible(false);
329
}
330
});
331
filedialog_load.addWindowListener(new WindowAdapter()//对话框增加适配器
332
{public void windowClosing(WindowEvent e)
333
{ filedialog_load.setVisible(false);
334
}
335
});
336
addWindowListener(new WindowAdapter()
337
{public void windowClosing(WindowEvent e)
338
{ System.exit(0);}
339
});
340
text=new TextArea(10,10);
341
add(text,BorderLayout.CENTER);
342
}
343
public void actionPerformed(ActionEvent e)
344
{ if(e.getSource()==itemOpen)
345
{ filedialog_load.setVisible(true);
346
text.setText(null);
347
String s;
348
if(filedialog_load.getFile()!=null)
349
{
350
try{ File file= new
351
File(filedialog_load.getDirectory(),filedialog_load.getFile());
352
file_reader=new FileReader(file);
353
in=new BufferedReader(file_reader);
354
while((s=in.readLine())!=null)
355
text.append(s+'\n');
356
in.close();
357
file_reader.close();
358
}
359
catch(IOException e2){}
360
}
361
}
362
else if(e.getSource()==itemSave)
363
{ filedialog_save.setVisible(true);
364
if(filedialog_save.getFile()!=null)
365
{
366
try {
367
File file=new
368
File(filedialog_save.getDirectory(),filedialog_save.getFile());
369
tofile=new FileWriter(file);
370
out=new BufferedWriter(tofile);
371
out.write(text.getText(),0,(text.getText()).length());
372
out.flush();
373
out.close();
374
tofile.close();
375
}
376
catch(IOException e2){}
377
}
378
}
379
}
380
}
381![]()
382
//例子9
383
import java.awt.*;import java.io.*;
384
import java.awt.event.*;
385
public class Example20_9
386
{ public static void main(String args[])
387
{ try{
388
Runtime ce=Runtime.getRuntime();
389
ce.exec("java Example20_8");
390
File file=new File("c:/windows","Notepad.exe");
391
ce.exec(file.getAbsolutePath());
392
}
393
catch(Exception e){}
394
}
395
}
396![]()
397
//例子10
398
import java.io.*;
399
public class Example20_10
400
{ public static void main(String args[])
401
{ RandomAccessFile in_and_out=null;
402
int data[]={1,2,3,4,5,6,7,8,9,10};
403
try{ in_and_out=new RandomAccessFile("tom.dat","rw");
404
}
405
catch(Exception e){}
406
try{ for(int i=0;i<data.length;i++)
407
{ in_and_out.writeInt(data[i]);
408
}
409
for(long i=data.length-1;i>=0;i--) //一个int型数据占4个字节,我们从
410
{ in_and_out.seek(i*4); //文件的第36个字节读取最后面的一个整数,
411
//每隔4个字节往前读取一个整数:
412
System.out.print(","+in_and_out.readInt());
413
}
414
in_and_out.close();
415
}
416
catch(IOException e){}
417
}
418
}
419![]()
420
//例子11
421
import java.io.*;
422
class Example20_11
423
{ public static void main(String args[])
424
{ try{ RandomAccessFile in=new RandomAccessFile("Example20_11.java","rw");
425
long filePoint=0;
426
long fileLength=in.length();
427
while(filePoint<fileLength)
428
{ String s=in.readLine();
429
System.out.println(s);
430
filePoint=in.getFilePointer();
431
}
432
in.close();
433
}
434
catch(Exception e){}
435
}
436
}
437![]()
438
//例子12
439
import java.io.*;
440
import javax.swing.*;
441
import java.awt.*;import
442
java.awt.event.*;
443
import javax.swing.border.*;
444
class InputArea extends Panel
445
implements ActionListener
446
{ File f=null;
447
RandomAccessFile out;
448
Box baseBox ,boxV1,boxV2;
449
TextField name,email,phone;
450
Button button;
451
InputArea(File f)
452
{ setBackground(Color.cyan);
453
this.f=f;
454
name=new TextField(12);
455
email=new TextField(12);
456
phone=new TextField(12);
457
button=new Button("录入");
458
button.addActionListener(this);
459
boxV1=Box.createVerticalBox();
460
boxV1.add(new Label("输入姓名"));
461
boxV1.add(Box.createVerticalStrut(8));
462
boxV1.add(new Label("输入email"));
463
boxV1.add(Box.createVerticalStrut(8));
464
boxV1.add(new Label("输入电话"));
465
boxV1.add(Box.createVerticalStrut(8));
466
boxV1.add(new Label("单击录入"));
467
boxV2=Box.createVerticalBox();
468
boxV2.add(name);
469
boxV2.add(Box.createVerticalStrut(8));
470
boxV2.add(email);
471
boxV2.add(Box.createVerticalStrut(8));
472
boxV2.add(phone);
473
boxV2.add(Box.createVerticalStrut(8));
474
boxV2.add(button);
475
baseBox=Box.createHorizontalBox();
476
baseBox.add(boxV1);
477
baseBox.add(Box.createHorizontalStrut(10));
478
baseBox.add(boxV2);
479
add(baseBox);
480
}
481
public void actionPerformed(ActionEvent e)
482
{ try{
483
RandomAccessFile out=new RandomAccessFile(f,"rw");
484
if(f.exists())
485
{ long length=f.length();
486
out.seek(length);
487
}
488
out.writeUTF("姓名:"+name.getText());
489
out.writeUTF("eamil:"+email.getText());
490
out.writeUTF("电话:"+phone.getText());
491
out.close();
492
}
493
catch(IOException ee){}
494
}
495
}
496![]()
497
public class Example20_12 extends Frame implements ActionListener
498
{ File file=null;
499
MenuBar bar;
500
Menu fileMenu;
501
MenuItem 录入,显示;
502
TextArea show;
503
InputArea inputMessage;
504
CardLayout card=null; //卡片式布局.
505
Panel pCenter;
506
Example20_12()
507
{
508
file=new File("通讯录.txt");
509
录入=new MenuItem("录入");
510
显示=new MenuItem("显示");
511
bar=new MenuBar();
512
fileMenu=new Menu("菜单选项");
513
fileMenu.add(录入);
514
fileMenu.add(显示);
515
bar.add(fileMenu);
516
setMenuBar(bar);
517
录入.addActionListener(this);
518
显示.addActionListener(this);
519
inputMessage=new InputArea(file);
520
show=new TextArea(12,20);
521
card=new CardLayout();
522
pCenter=new Panel();
523
pCenter.setLayout(card);
524
pCenter.add("录入",inputMessage);
525
pCenter.add("显示",show);
526![]()
527
add(pCenter,BorderLayout.CENTER);
528
addWindowListener(new WindowAdapter()
529
{ public void windowClosing(WindowEvent e)
530
{
531
System.exit(0);
532
}
533
});
534
setVisible(true);
535
setBounds(100,50,420,380);
536
validate();
537
}
538
public void actionPerformed(ActionEvent e)
539
{
540
if(e.getSource()==录入)
541
{
542
card.show(pCenter,"录入");
543
}
544
else if(e.getSource()==显示)
545
{ int number=1;
546
card.show(pCenter,"显示");
547
try{ RandomAccessFile in=new RandomAccessFile(file,"r");
548
String 姓名=null;
549
while((姓名=in.readUTF())!=null)
550
{ show.append("\n"+number+" "+姓名);
551
show.append(in.readUTF()); //读取email.
552
show.append(in.readUTF()); //读取phone
553
show.append("\n------------------------- ");
554
number++;
555
}
556
in.close();
557
}
558
catch(Exception ee){}
559
}
560
}
561
public static void main(String args[])
562
{ new Example20_12();
563
}
564
}
565![]()
566
//例子13
567
import java.io.*;
568
public class Example20_13
569
{ public static void main(String args[])
570
{ try
571
{ FileOutputStream fos=new FileOutputStream("jerry.dat");
572
DataOutputStream out_data=new DataOutputStream(fos);
573
out_data.writeInt(100);out_data.writeInt(10012);
574
out_data.writeLong(123456);
575
out_data.writeFloat(3.1415926f); out_data.writeFloat(2.789f);
576
out_data.writeDouble(987654321.1234);
577
out_data.writeBoolean(true);out_data.writeBoolean(false);
578
out_data.writeChars("i am ookk");
579
}
580
catch(IOException e){}
581
try
582
{ FileInputStream fis=new FileInputStream("jerry.dat");
583
DataInputStream in_data=new DataInputStream(fis);
584
System.out.println(":"+in_data.readInt());//读取第1个int整数。
585
System.out.println(":"+in_data.readInt());//读取第2个int整数。
586
System.out.println(":"+in_data.readLong()); //读取long整数 。
587
System.out.println(":"+in_data.readFloat());//读取第1个float数。
588
System.out.println(":"+in_data.readFloat());//读取第2个float数。
589
System.out.println(":"+in_data.readDouble());
590
System.out.println(":"+in_data.readBoolean());//读取第1个boolean。
591
System.out.println(":"+in_data.readBoolean());//读取第2个boolean。
592
char c;
593
while((c=in_data.readChar())!='\0') //'\0'表示空字符。
594
System.out.print(c);
595
}
596
catch(IOException e){}
597
}
598
}
599![]()
600
//例子14
601
import java.awt.*;import java.awt.event.*;
602
import java.io.*;
603
public class Example20_14 extends Frame implements ActionListener
604
{ TextArea text=null; Button 读入=null,写出=null;
605
FileInputStream file_in=null; FileOutputStream file_out=null;
606
ObjectInputStream object_in=null; //对象输入流。
607
ObjectOutputStream object_out=null; //对象输出流。
608
Example20_14()
609
{ setLayout(new FlowLayout()); text=new TextArea(6,10);
610
读入=new Button("读入对象"); 写出=new Button("写出对象");
611
读入.addActionListener(this);写出.addActionListener(this);
612
setVisible(true); add(text);add(读入);add(写出);
613
addWindowListener(new WindowAdapter()
614
{ public void windowClosing(WindowEvent e)
615
{ System.exit(0);
616
}
617
});
618
pack();setSize(300,300);
619
}
620
public void actionPerformed(ActionEvent e)
621
{ if(e.getSource()==写出)
622
{ try{ file_out=new FileOutputStream("tom.txt");
623
object_out=new ObjectOutputStream(file_out);//创建对象输出流。
624
object_out.writeObject(text); //写对象到文件中。
625
object_out.close();
626
}
627
catch(IOException event){}
628
}
629
else if(e.getSource()==读入)
630
{ try{ file_in=new FileInputStream("tom.txt");
631
object_in=new ObjectInputStream(file_in); //创建对象输入流。
632
TextArea temp=(TextArea)object_in.readObject();//从文件中读入对象。
633
temp.setBackground(Color.pink); this.add(temp);//添加该对象到窗口。
634
this.pack();this.setSize(600,600);
635
object_in.close();
636
}
637
catch(ClassNotFoundException event)
638
{ System.out.println("不能读出对象");
639
}
640
catch(IOException event)
641
{ System.out.println("can not read file");
642
}
643
}
644
}
645
public static void main(String args[])
646
{ Example20_14 win=new Example20_14();
647
}
648
}
649![]()
650
//例子15
651
import java.io.*;
652
class Student implements Serializable//实现接口Serializable的Student类。
653
{ String name=null;double height;
654
Student(String name,double height)
655
{ this.name=name;this.height=height;
656
}
657
public void setHeight (double c)
658
{ this.height=c;
659
}
660
}
661
public class Example20_15
662
{ public static void main(String args[])
663
{ Student zhang=new Student("zhang ping",1.65);
664
try{ FileOutputStream file_out=new FileOutputStream("s.txt");
665
ObjectOutputStream object_out=new ObjectOutputStream(file_out);
666
object_out.writeObject(zhang);
667
System.out.println(zhang.name+"的身高是:"+zhang.height);
668
FileInputStream file_in=new FileInputStream("s.txt");
669
ObjectInputStream object_in=new ObjectInputStream(file_in);
670
zhang=(Student)object_in.readObject();
671
zhang.setHeight(1.78); //修改身高。
672
System.out.println(zhang.name+"现在的身高是:"+zhang.height);
673
}
674
catch(ClassNotFoundException event)
675
{ System.out.println("不能读出对象");
676
}
677
catch(IOException event)
678
{ System.out.println("can not read file"+event);
679
}
680
}
681
}
682![]()
683
//例子16
684
import java.awt.*;import java.io.*;import java.awt.event.*;
685
public class Example20_16
686
{ public static void main(String args[])
687
{ JDK f=new JDK();
688
f.pack();
689
f.addWindowListener(new WindowAdapter() //窗口增加适配器。
690
{public void windowClosing(WindowEvent e)
691
{ System.exit(0);
692
}
693
});
694
f.setBounds(100,120,700,360);
695
f.setVisible(true);
696
}
697
}
698
class JDK extends Frame implements ActionListener,Runnable
699
{ Thread compiler=null; //负责编译的线程。
700
Thread run_prom=null; //负责运行程序的线程。
701
boolean bn=true;
702
CardLayout mycard;
703
Panel p=new Panel();
704
File file_saved=null;
705
TextArea input_text=new TextArea(),//程序输入区。
706
compiler_text=new TextArea(), //编译出错显示区。
707
dos_out_text=new TextArea(); //程序运行时,负责显示在dos窗口的输出信息。
708
Button button_input_text,button_compiler_text,
709
button_compiler,button_run_prom,button_see_doswin;
710
TextField input_flie_name_text=new TextField("输入被编译的文件名字.java");
711
TextField run_file_name_text=new TextField("输入应用程序主类的名字");
712
JDK()
713
{ super("Java编程小软件");
714
mycard=new CardLayout();
715
compiler=new Thread(this);
716
run_prom=new Thread(this);
717
button_input_text=new Button("程序输入区(白色)");
718
button_compiler_text=new Button("编译结果区(粉色)");
719
button_compiler=new Button("编译程序");
720
button_run_prom=new Button("运行应用程序");
721
button_see_doswin=new Button("查看应用程序运行时在dos窗口输出的信息");
722
p.setLayout(mycard);
723
p.add("input",input_text);p.add("compiler",compiler_text);
724
p.add("dos",dos_out_text);
725
add(p,"Center");
726
add( button_see_doswin,"South");
727
compiler_text.setBackground(Color.pink);
728
dos_out_text.setBackground(Color.blue);
729
Panel p1=new Panel();p1.setLayout(new GridLayout(4,2));
730
p1.add(new Label("按扭输入源程序:"));p1.add(button_input_text);
731
p1.add(new Label("按扭看编译结果:"));p1.add(button_compiler_text);
732
p1.add(input_flie_name_text); p1.add(button_compiler);
733
p1.add(run_file_name_text); p1.add(button_run_prom);
734
add(p1,BorderLayout.NORTH);
735
button_input_text.addActionListener(this);
736
button_compiler_text.addActionListener(this);
737
button_compiler.addActionListener(this);
738
button_run_prom.addActionListener(this);
739
button_see_doswin.addActionListener(this);
740
}
741
public void actionPerformed(ActionEvent e)
742
{ if(e.getSource()==button_input_text)
743
{ mycard.show(p,"input");
744
}
745
else if(e.getSource()==button_compiler_text)
746
{ mycard.show(p,"compiler");
747
}
748
else if(e.getSource()==button_see_doswin)
749
{ mycard.show(p,"dos");
750
}
751
else if(e.getSource()==button_compiler)
752
{ if(!(compiler.isAlive()))
753
{ compiler=new Thread(this);
754
}
755
try{ compiler.start();
756
}
757
catch(Exception eee){}
758
mycard.show(p,"compiler");
759
}
760
else if(e.getSource()==button_run_prom)
761
{ if(!(run_prom.isAlive()))
762
{ run_prom =new Thread(this);
763
}
764
try{ run_prom.start();
765
}
766
catch(Exception eee){}
767
mycard.show(p,"dos");
768
}
769
}
770
public void run()
771
{ if(Thread.currentThread()==compiler)
772
{ compiler_text.setText(null);
773
String temp=input_text.getText().trim();
774
byte buffer[]=temp.getBytes();
775
int b=buffer.length;
776
String flie_name=input_flie_name_text.getText().trim();
777
try{ file_saved=new File(flie_name);
778
FileOutputStream writefile=new FileOutputStream(file_saved);
779
writefile.write(buffer,0,b);writefile.close();
780
}
781
catch(IOException e5)
782
{ System.out.println("Error ");
783
}
784
try{ Runtime ce=Runtime.getRuntime();
785
InputStream in=
786
ce.exec("javac "+flie_name).getErrorStream();
787
BufferedInputStream bin=new BufferedInputStream(in);
788
byte shuzu[]=new byte[100];
789
int n;boolean bn=true;
790
while((n=bin.read(shuzu,0,100))!=-1)
791
{ String s=null;
792
s=new String(shuzu,0,n);
793
compiler_text.append(s);
794
if(s!=null) bn=false;
795
}
796
if(bn)
797
{ compiler_text.append("编译正确");
798
}
799
}
800
catch(IOException e1){}
801
}
802
else if(Thread.currentThread()==run_prom)
803
{ dos_out_text.setText(null);
804
try{ Runtime ce=Runtime.getRuntime();
805
String path=run_file_name_text.getText().trim();
806
InputStream in=ce.exec("java "+path).getInputStream();
807
BufferedInputStream bin=new BufferedInputStream(in);
808
byte zu[]=new byte[150];
809
int m;String s=null;
810
while((m=bin.read(zu,0,150))!=-1)
811
{ s=new String(zu,0,m);
812
dos_out_text.append(s);
813
}
814
}
815
catch(IOException e1){}
816
}
817
}
818
}
819![]()
//例子12
import java.io.*;3
class Example20_1 4
{ public static void main(String args[])5
{ File f1=new File("F:\\8000","Example20_1.java");6
File f2=new File("F:\\8000");7
System.out.println("文件Example20_1是可读的吗:"+f1.canRead());8
System.out.println("文件Example20_1的长度:"+f1.length());9
System.out.println("文件Example20_1的绝对路径:"+f1.getAbsolutePath());10
System.out.println("F:\\8000:是目录吗?"+f2.isDirectory());11
}12
}13

14
//例子215
import java.io.*;16
class FileAccept implements FilenameFilter 17
{ String str=null;18
FileAccept(String s)19
{ str="."+s;20
}21
public boolean accept(File dir,String name)22
{ return name.endsWith(str);23
} 24
}25
public class Example20_226
{ public static void main(String args[])27
{ File dir=new File("F:/8000");28
FileAccept acceptCondition=new FileAccept("java");29
String fileName[]=dir.list(acceptCondition);30
for(int i=0;i<5;i++)31
{ System.out.println(fileName[i]);32
}33
}34
}35

36
//例子337
import java.io.*;import java.awt.*;import java.awt.event.*;38
class Example20_339
{ public static void main(String args[])40
{ int b;41
TextArea text;42
Frame window=new Frame();43
byte tom[]=new byte[25];44
window.setSize(100,100);text=new TextArea(10,16);45
window.setVisible(true);window.add(text,BorderLayout.CENTER);46
window.pack();47
window.addWindowListener(new WindowAdapter()48
{ public void windowClosing(WindowEvent e)49
{ System.exit(0);50
}51
}); 52
53
try{ File f=new File("F:\\8000","Example20_1.java");54
FileInputStream readfile=new FileInputStream(f);55
while((b=readfile.read(tom,0,25))!=-1) 56
{57
String s=new String (tom,0,b);58
System.out.println(s);59
text.append(s); 60
}61
readfile.close();62
}63
catch(IOException e)64
{ System.out.println("File read Error");65
}66
}67
}68

69
//例子470
import java.io.*;71
class Example20_472
{ public static void main(String args[])73
{ int b;74
byte buffer[]=new byte[100];75
try{ System.out.println("输入一行文本,并存入磁盘:");76
b=System.in.read(buffer); //把从键盘敲入的字符存入buffer。77
FileOutputStream writefile=new FileOutputStream("line.txt");78
writefile.write(buffer,0,b); // 通过流把 buffer写入到文件line.txt。79
}80
catch(IOException e)81
{ System.out.println("Error ");82
}83
}84
}85

86
//例子587
import java.io.*;import java.awt.*;import java.awt.event.*;88
class Example20_589
{ public static void main(String args[])90
{ char a[]="今晚10点发起总攻".toCharArray(); 91
int n=0,m=0;92
try{ File f=new File("F:\\8000","secret.txt");93
for(int i=0;i<a.length;i++)94
{ a[i]=(char)(a[i]^'R');95
}96
FileWriter out=new FileWriter(f);97
out.write(a,0,a.length);98
out.close();99
FileReader in=new FileReader(f);100
int length=(int)f.length();101
char tom[]=new char[length];102
while((n=in.read(tom,0,length))!=-1) 103
{ String s=new String (tom,0,n);104
m=n; 105
System.out.println("密文:"+s);106
}107
in.close();108
for(int i=0;i<m;i++)109
{ tom[i]=(char)(tom[i]^'R');110
}111
String 明文=new String(tom,0,m);112
System.out.println("明文:"+明文);113
}114
catch(IOException e)115
{ System.out.println("File read Error");116
}117
}118
}119

120
//例子6121
import java.io.*;122
import java.awt.*;123
import java.awt.event.*;124
class EWindow extends Frame implements ActionListener125
{ TextArea text; 126
Button buttonRead,buttonWrite;127
BufferedReader bufferIn; 128
FileReader in;129
BufferedWriter bufferOut; 130
FileWriter out;131
EWindow()132
{ super("流的读取");133
text=new TextArea(10,10);text.setBackground(Color.cyan);134
buttonRead =new Button("读取"); 135
buttonRead.addActionListener(this);136
buttonWrite =new Button("写出"); 137
buttonWrite.addActionListener(this);138
setLayout(new BorderLayout());139
setSize(340,340);140
setVisible(true);141
add(text,BorderLayout.CENTER);142
Panel pNorth=new Panel();143
pNorth.add(buttonRead);pNorth.add(buttonWrite);144
pNorth.validate();145
add(BorderLayout.NORTH,pNorth);146
addWindowListener(new WindowAdapter()147
{ public void windowClosing(WindowEvent e)148
{ System.exit(0);149
}150
});151
} 152
public void actionPerformed(ActionEvent e)153
{ String s;154
if(e.getSource()==buttonRead)155
{ try{ text.setText(null);156
File f=new File("F:\\8000\\","E.java");157
in=new FileReader(f);158
bufferIn=new BufferedReader(in);159
while((s=bufferIn.readLine())!=null)160
{ text.append(s+'\n'); 161
}162
bufferIn.close();163
in.close();164
}165
catch(IOException exp){System.out.println(exp);} 166
}167
if(e.getSource()==buttonWrite)168
{ try { File f=new File("F:\\8000\\","E.java");169
FileWriter out=new FileWriter(f);170
BufferedWriter bufferOut=new BufferedWriter(out);171
bufferOut.write(text.getText(),0,(text.getText()).length());172
bufferOut.flush();173
bufferOut.close();174
out.close();175
}176
catch(IOException exp){ System.out.println(exp);}177
}178
}179
}180
public class Example20_6181
{ public static void main(String args[])182
{ EWindow w=new EWindow();183
w.validate();184
}185
}186

187
//例子7188
import java.util.*;import java.io.*;189
import java.awt.*;import java.awt.event.*;190
class EWindow extends Frame implements ActionListener,ItemListener191
{ String str[]=new String[7];String s;192
FileReader file;193
BufferedReader in; 194
Button start,next;195
Checkbox box[];196
TextField 题目,分数;197
int score=0; 198
CheckboxGroup age=new CheckboxGroup();199
EWindow()200
{ super("英语单词学习");201
分数=new TextField(10);题目=new TextField(70);202
start=new Button("重新练习");start.addActionListener(this);203
next=new Button("下一题目");next.addActionListener(this);204
box=new Checkbox[4];205
for(int i=0;i<=3;i++)206
{ box[i]=new Checkbox("",false,age);207
box[i].addItemListener(this); 208
} 209
try { file=new FileReader("English.txt");210
in=new BufferedReader(file);211
}212
catch(IOException e){} 213
setBounds(100,100,400,320); setVisible(true);214
setLayout(new GridLayout(4,1));215
setBackground(Color.pink);216
Panel p1=new Panel(),p2=new Panel(),217
p3=new Panel() ,p4=new Panel(),p5=new Panel();218
p1.add(new Label("题目:"));p1.add(题目);219
p2.add(new Label("选择答案:")); 220
for(int i=0;i<=3;i++)221
{ p2.add(box[i]);222
} 223
p3.add(new Label("您的得分:"));p3.add(分数);224
p4.add(start); p4.add(next);225
add(p1); add(p2);add(p3); add(p4);226
addWindowListener(new WindowAdapter()227
{public void windowClosing(WindowEvent e)228
{ System.exit(0); 229
}230
});231
reading();232
} 233
public void reading()234
{ int i=0; 235
try { s=in.readLine();236
if(!(s.startsWith("endend")))237
{ StringTokenizer tokenizer=new StringTokenizer(s,"#"); 238
while(tokenizer.hasMoreTokens())239
{ str[i]=tokenizer.nextToken();240
i++;241
}242
题目.setText(str[0]);243
for(int j=1;j<=4;j++)244
{ box[j-1].setLabel(str[j]);245
} 246
}247
else if(s.startsWith("endend"))248
{ 题目.setText("学习完毕"); 249
for(int j=0;j<4;j++)250
{ box[j].setLabel("end"); 251
in.close();file.close();252
} 253
}254
}255
catch(Exception exp){ 题目.setText("无试题文件") ; } 256
}257
public void actionPerformed(ActionEvent event)258
{ if(event.getSource()==start)259
{ score=0;260
分数.setText("得分: "+score);261
try { file=new FileReader("English.txt");262
in=new BufferedReader(file);263
}264
catch(IOException e){} 265
reading(); 266
}267
if(event.getSource()==next)268
{ reading();269
for(int j=0;j<4;j++)270
{ 271
box[j].setEnabled(true); 272
}273
}274
}275
public void itemStateChanged(ItemEvent e)276
{ for(int j=0;j<4;j++)277
{ if(box[j].getLabel().equals(str[5])&&box[j].getState())278
{ score++;279
分数.setText("得分: "+score);280
}281
box[j].setEnabled(false); 282
}283
}284
}285
public class Example20_7286
{ public static void main(String args[])287
{ EWindow w=new EWindow();288
w.pack();289
}290
}291

292
//例子8293
import java.awt.*;import java.io.*;294
import java.awt.event.*;295
public class Example20_8296
{ public static void main(String args[])297
{ FileWindows win=new FileWindows();298
}299
}300
class FileWindows extends Frame implements ActionListener301
{ FileDialog filedialog_save,filedialog_load;//声明2个文件对话筐302
MenuBar menubar;303
Menu menu;304
MenuItem itemOpen,itemSave;305
TextArea text;306
BufferedReader in; 307
FileReader file_reader;308
BufferedWriter out; 309
FileWriter tofile;310
FileWindows()311
{ super("带文件对话框的窗口"); 312
setSize(260,270); 313
setVisible(true); 314
menubar=new MenuBar(); 315
menu=new Menu("文件"); 316
itemOpen=new MenuItem("打开文件");317
itemSave=new MenuItem("保存文件"); 318
itemOpen.addActionListener(this); 319
itemSave.addActionListener(this);320
menu.add(itemOpen);321
menu.add(itemSave); 322
menubar.add(menu); 323
setMenuBar(menubar); 324
filedialog_save=new FileDialog(this,"保存文件话框",FileDialog.SAVE);325
filedialog_load=new FileDialog(this,"打开文件话框",FileDialog.LOAD);326
filedialog_save.addWindowListener(new WindowAdapter()327
{public void windowClosing(WindowEvent e)328
{ filedialog_save.setVisible(false);329
}330
});331
filedialog_load.addWindowListener(new WindowAdapter()//对话框增加适配器332
{public void windowClosing(WindowEvent e)333
{ filedialog_load.setVisible(false);334
}335
});336
addWindowListener(new WindowAdapter() 337
{public void windowClosing(WindowEvent e)338
{ System.exit(0);}339
});340
text=new TextArea(10,10);341
add(text,BorderLayout.CENTER);342
}343
public void actionPerformed(ActionEvent e) 344
{ if(e.getSource()==itemOpen)345
{ filedialog_load.setVisible(true);346
text.setText(null);347
String s;348
if(filedialog_load.getFile()!=null)349
{350
try{ File file= new 351
File(filedialog_load.getDirectory(),filedialog_load.getFile());352
file_reader=new FileReader(file);353
in=new BufferedReader(file_reader);354
while((s=in.readLine())!=null)355
text.append(s+'\n'); 356
in.close();357
file_reader.close();358
}359
catch(IOException e2){}360
}361
}362
else if(e.getSource()==itemSave)363
{ filedialog_save.setVisible(true);364
if(filedialog_save.getFile()!=null)365
{366
try {367
File file=new368
File(filedialog_save.getDirectory(),filedialog_save.getFile());369
tofile=new FileWriter(file);370
out=new BufferedWriter(tofile);371
out.write(text.getText(),0,(text.getText()).length());372
out.flush();373
out.close();374
tofile.close();375
}376
catch(IOException e2){}377
}378
}379
} 380
}381

382
//例子9383
import java.awt.*;import java.io.*;384
import java.awt.event.*;385
public class Example20_9386
{ public static void main(String args[])387
{ try{388
Runtime ce=Runtime.getRuntime();389
ce.exec("java Example20_8");390
File file=new File("c:/windows","Notepad.exe");391
ce.exec(file.getAbsolutePath());392
}393
catch(Exception e){} 394
} 395
}396

397
//例子10398
import java.io.*;399
public class Example20_10400
{ public static void main(String args[])401
{ RandomAccessFile in_and_out=null;402
int data[]={1,2,3,4,5,6,7,8,9,10};403
try{ in_and_out=new RandomAccessFile("tom.dat","rw");404
}405
catch(Exception e){}406
try{ for(int i=0;i<data.length;i++)407
{ in_and_out.writeInt(data[i]);408
} 409
for(long i=data.length-1;i>=0;i--) //一个int型数据占4个字节,我们从410
{ in_and_out.seek(i*4); //文件的第36个字节读取最后面的一个整数,411
//每隔4个字节往前读取一个整数:412
System.out.print(","+in_and_out.readInt());413
}414
in_and_out.close();415
}416
catch(IOException e){} 417
}418
}419

420
//例子11421
import java.io.*;422
class Example20_11 423
{ public static void main(String args[])424
{ try{ RandomAccessFile in=new RandomAccessFile("Example20_11.java","rw");425
long filePoint=0;426
long fileLength=in.length();427
while(filePoint<fileLength)428
{ String s=in.readLine();429
System.out.println(s);430
filePoint=in.getFilePointer();431
}432
in.close();433
}434
catch(Exception e){}435
}436
}437

438
//例子12439
import java.io.*;440
import javax.swing.*;441
import java.awt.*;import 442
java.awt.event.*;443
import javax.swing.border.*;444
class InputArea extends Panel 445
implements ActionListener446
{ File f=null;447
RandomAccessFile out;448
Box baseBox ,boxV1,boxV2; 449
TextField name,email,phone;450
Button button;451
InputArea(File f)452
{ setBackground(Color.cyan);453
this.f=f;454
name=new TextField(12);455
email=new TextField(12); 456
phone=new TextField(12);457
button=new Button("录入");458
button.addActionListener(this);459
boxV1=Box.createVerticalBox();460
boxV1.add(new Label("输入姓名"));461
boxV1.add(Box.createVerticalStrut(8));462
boxV1.add(new Label("输入email"));463
boxV1.add(Box.createVerticalStrut(8));464
boxV1.add(new Label("输入电话"));465
boxV1.add(Box.createVerticalStrut(8));466
boxV1.add(new Label("单击录入"));467
boxV2=Box.createVerticalBox();468
boxV2.add(name);469
boxV2.add(Box.createVerticalStrut(8));470
boxV2.add(email);471
boxV2.add(Box.createVerticalStrut(8));472
boxV2.add(phone);473
boxV2.add(Box.createVerticalStrut(8));474
boxV2.add(button);475
baseBox=Box.createHorizontalBox();476
baseBox.add(boxV1);477
baseBox.add(Box.createHorizontalStrut(10));478
baseBox.add(boxV2);479
add(baseBox); 480
}481
public void actionPerformed(ActionEvent e)482
{ try{483
RandomAccessFile out=new RandomAccessFile(f,"rw");484
if(f.exists())485
{ long length=f.length();486
out.seek(length);487
}488
out.writeUTF("姓名:"+name.getText());489
out.writeUTF("eamil:"+email.getText());490
out.writeUTF("电话:"+phone.getText());491
out.close();492
}493
catch(IOException ee){}494
}495
}496

497
public class Example20_12 extends Frame implements ActionListener498
{ File file=null;499
MenuBar bar;500
Menu fileMenu;501
MenuItem 录入,显示;502
TextArea show;503
InputArea inputMessage;504
CardLayout card=null; //卡片式布局.505
Panel pCenter;506
Example20_12()507
{ 508
file=new File("通讯录.txt");509
录入=new MenuItem("录入");510
显示=new MenuItem("显示");511
bar=new MenuBar();512
fileMenu=new Menu("菜单选项");513
fileMenu.add(录入);514
fileMenu.add(显示);515
bar.add(fileMenu);516
setMenuBar(bar);517
录入.addActionListener(this);518
显示.addActionListener(this);519
inputMessage=new InputArea(file);520
show=new TextArea(12,20); 521
card=new CardLayout();522
pCenter=new Panel();523
pCenter.setLayout(card);524
pCenter.add("录入",inputMessage);525
pCenter.add("显示",show);526

527
add(pCenter,BorderLayout.CENTER);528
addWindowListener(new WindowAdapter()529
{ public void windowClosing(WindowEvent e)530
{531
System.exit(0);532
}533
});534
setVisible(true);535
setBounds(100,50,420,380);536
validate();537
}538
public void actionPerformed(ActionEvent e)539
{540
if(e.getSource()==录入)541
{542
card.show(pCenter,"录入");543
}544
else if(e.getSource()==显示)545
{ int number=1;546
card.show(pCenter,"显示");547
try{ RandomAccessFile in=new RandomAccessFile(file,"r");548
String 姓名=null; 549
while((姓名=in.readUTF())!=null) 550
{ show.append("\n"+number+" "+姓名);551
show.append(in.readUTF()); //读取email.552
show.append(in.readUTF()); //读取phone553
show.append("\n------------------------- ");554
number++;555
}556
in.close();557
}558
catch(Exception ee){}559
}560
}561
public static void main(String args[])562
{ new Example20_12();563
}564
}565

566
//例子13567
import java.io.*;568
public class Example20_13569
{ public static void main(String args[])570
{ try 571
{ FileOutputStream fos=new FileOutputStream("jerry.dat");572
DataOutputStream out_data=new DataOutputStream(fos);573
out_data.writeInt(100);out_data.writeInt(10012);574
out_data.writeLong(123456); 575
out_data.writeFloat(3.1415926f); out_data.writeFloat(2.789f);576
out_data.writeDouble(987654321.1234);577
out_data.writeBoolean(true);out_data.writeBoolean(false);578
out_data.writeChars("i am ookk");579
} 580
catch(IOException e){}581
try582
{ FileInputStream fis=new FileInputStream("jerry.dat");583
DataInputStream in_data=new DataInputStream(fis);584
System.out.println(":"+in_data.readInt());//读取第1个int整数。585
System.out.println(":"+in_data.readInt());//读取第2个int整数。586
System.out.println(":"+in_data.readLong()); //读取long整数 。587
System.out.println(":"+in_data.readFloat());//读取第1个float数。588
System.out.println(":"+in_data.readFloat());//读取第2个float数。589
System.out.println(":"+in_data.readDouble()); 590
System.out.println(":"+in_data.readBoolean());//读取第1个boolean。591
System.out.println(":"+in_data.readBoolean());//读取第2个boolean。592
char c;593
while((c=in_data.readChar())!='\0') //'\0'表示空字符。594
System.out.print(c);595
} 596
catch(IOException e){}597
}598
}599

600
//例子14601
import java.awt.*;import java.awt.event.*;602
import java.io.*;603
public class Example20_14 extends Frame implements ActionListener604
{ TextArea text=null; Button 读入=null,写出=null;605
FileInputStream file_in=null; FileOutputStream file_out=null;606
ObjectInputStream object_in=null; //对象输入流。607
ObjectOutputStream object_out=null; //对象输出流。608
Example20_14()609
{ setLayout(new FlowLayout()); text=new TextArea(6,10);610
读入=new Button("读入对象"); 写出=new Button("写出对象");611
读入.addActionListener(this);写出.addActionListener(this);612
setVisible(true); add(text);add(读入);add(写出);613
addWindowListener(new WindowAdapter()614
{ public void windowClosing(WindowEvent e)615
{ System.exit(0);616
}617
});618
pack();setSize(300,300);619
}620
public void actionPerformed(ActionEvent e)621
{ if(e.getSource()==写出)622
{ try{ file_out=new FileOutputStream("tom.txt");623
object_out=new ObjectOutputStream(file_out);//创建对象输出流。624
object_out.writeObject(text); //写对象到文件中。625
object_out.close();626
}627
catch(IOException event){}628
}629
else if(e.getSource()==读入)630
{ try{ file_in=new FileInputStream("tom.txt");631
object_in=new ObjectInputStream(file_in); //创建对象输入流。632
TextArea temp=(TextArea)object_in.readObject();//从文件中读入对象。633
temp.setBackground(Color.pink); this.add(temp);//添加该对象到窗口。634
this.pack();this.setSize(600,600);635
object_in.close();636
}637
catch(ClassNotFoundException event)638
{ System.out.println("不能读出对象");639
}640
catch(IOException event)641
{ System.out.println("can not read file");642
}643
}644
}645
public static void main(String args[])646
{ Example20_14 win=new Example20_14();647
}648
}649

650
//例子15651
import java.io.*;652
class Student implements Serializable//实现接口Serializable的Student类。653
{ String name=null;double height; 654
Student(String name,double height)655
{ this.name=name;this.height=height;656
}657
public void setHeight (double c)658
{ this.height=c;659
}660
}661
public class Example20_15662
{ public static void main(String args[])663
{ Student zhang=new Student("zhang ping",1.65);664
try{ FileOutputStream file_out=new FileOutputStream("s.txt");665
ObjectOutputStream object_out=new ObjectOutputStream(file_out);666
object_out.writeObject(zhang); 667
System.out.println(zhang.name+"的身高是:"+zhang.height); 668
FileInputStream file_in=new FileInputStream("s.txt");669
ObjectInputStream object_in=new ObjectInputStream(file_in);670
zhang=(Student)object_in.readObject();671
zhang.setHeight(1.78); //修改身高。672
System.out.println(zhang.name+"现在的身高是:"+zhang.height);673
}674
catch(ClassNotFoundException event)675
{ System.out.println("不能读出对象");676
}677
catch(IOException event)678
{ System.out.println("can not read file"+event);679
}680
}681
}682

683
//例子16684
import java.awt.*;import java.io.*;import java.awt.event.*;685
public class Example20_16686
{ public static void main(String args[])687
{ JDK f=new JDK();688
f.pack();689
f.addWindowListener(new WindowAdapter() //窗口增加适配器。690
{public void windowClosing(WindowEvent e)691
{ System.exit(0);692
}693
});694
f.setBounds(100,120,700,360);695
f.setVisible(true);696
}697
}698
class JDK extends Frame implements ActionListener,Runnable699
{ Thread compiler=null; //负责编译的线程。700
Thread run_prom=null; //负责运行程序的线程。701
boolean bn=true;702
CardLayout mycard;703
Panel p=new Panel();704
File file_saved=null;705
TextArea input_text=new TextArea(),//程序输入区。706
compiler_text=new TextArea(), //编译出错显示区。707
dos_out_text=new TextArea(); //程序运行时,负责显示在dos窗口的输出信息。708
Button button_input_text,button_compiler_text,709
button_compiler,button_run_prom,button_see_doswin;710
TextField input_flie_name_text=new TextField("输入被编译的文件名字.java");711
TextField run_file_name_text=new TextField("输入应用程序主类的名字");712
JDK()713
{ super("Java编程小软件");714
mycard=new CardLayout();715
compiler=new Thread(this);716
run_prom=new Thread(this);717
button_input_text=new Button("程序输入区(白色)");718
button_compiler_text=new Button("编译结果区(粉色)");719
button_compiler=new Button("编译程序");720
button_run_prom=new Button("运行应用程序");721
button_see_doswin=new Button("查看应用程序运行时在dos窗口输出的信息");722
p.setLayout(mycard);723
p.add("input",input_text);p.add("compiler",compiler_text);724
p.add("dos",dos_out_text);725
add(p,"Center");726
add( button_see_doswin,"South"); 727
compiler_text.setBackground(Color.pink);728
dos_out_text.setBackground(Color.blue);729
Panel p1=new Panel();p1.setLayout(new GridLayout(4,2));730
p1.add(new Label("按扭输入源程序:"));p1.add(button_input_text);731
p1.add(new Label("按扭看编译结果:"));p1.add(button_compiler_text); 732
p1.add(input_flie_name_text); p1.add(button_compiler);733
p1.add(run_file_name_text); p1.add(button_run_prom);734
add(p1,BorderLayout.NORTH); 735
button_input_text.addActionListener(this);736
button_compiler_text.addActionListener(this);737
button_compiler.addActionListener(this); 738
button_run_prom.addActionListener(this);739
button_see_doswin.addActionListener(this);740
}741
public void actionPerformed(ActionEvent e) 742
{ if(e.getSource()==button_input_text)743
{ mycard.show(p,"input");744
}745
else if(e.getSource()==button_compiler_text)746
{ mycard.show(p,"compiler");747
}748
else if(e.getSource()==button_see_doswin)749
{ mycard.show(p,"dos");750
}751
else if(e.getSource()==button_compiler)752
{ if(!(compiler.isAlive()))753
{ compiler=new Thread(this);754
}755
try{ compiler.start();756
}757
catch(Exception eee){}758
mycard.show(p,"compiler");759
}760
else if(e.getSource()==button_run_prom)761
{ if(!(run_prom.isAlive()))762
{ run_prom =new Thread(this);763
}764
try{ run_prom.start();765
}766
catch(Exception eee){} 767
mycard.show(p,"dos");768
}769
}770
public void run()771
{ if(Thread.currentThread()==compiler)772
{ compiler_text.setText(null); 773
String temp=input_text.getText().trim(); 774
byte buffer[]=temp.getBytes(); 775
int b=buffer.length;776
String flie_name=input_flie_name_text.getText().trim();777
try{ file_saved=new File(flie_name);778
FileOutputStream writefile=new FileOutputStream(file_saved);779
writefile.write(buffer,0,b);writefile.close();780
}781
catch(IOException e5)782
{ System.out.println("Error ");783
}784
try{ Runtime ce=Runtime.getRuntime();785
InputStream in=786
ce.exec("javac "+flie_name).getErrorStream();787
BufferedInputStream bin=new BufferedInputStream(in);788
byte shuzu[]=new byte[100];789
int n;boolean bn=true;790
while((n=bin.read(shuzu,0,100))!=-1)791
{ String s=null;792
s=new String(shuzu,0,n);793
compiler_text.append(s);794
if(s!=null) bn=false;795
}796
if(bn) 797
{ compiler_text.append("编译正确"); 798
} 799
} 800
catch(IOException e1){} 801
}802
else if(Thread.currentThread()==run_prom)803
{ dos_out_text.setText(null);804
try{ Runtime ce=Runtime.getRuntime();805
String path=run_file_name_text.getText().trim();806
InputStream in=ce.exec("java "+path).getInputStream();807
BufferedInputStream bin=new BufferedInputStream(in);808
byte zu[]=new byte[150];809
int m;String s=null;810
while((m=bin.read(zu,0,150))!=-1)811
{ s=new String(zu,0,m);812
dos_out_text.append(s);813
}814
} 815
catch(IOException e1){} 816
} 817
}818
}819




浙公网安备 33010602011771号