admin 管理员组

文章数量: 1086019


2024年12月30日发(作者:创新驱动发展战略的战略目标)

8.4在多线程程序中,要考虑互斥的原因是什么?在Java中如何解决?

答:多线程之间要共享资源,为了保护资源在使用时,不被其他线程使用。

在Java语言中,使用关键字synchronized定义临界段,能对共享对象的操作上锁。

8.5在多线程程序中,要考虑同步的原因是什么?在Java中如何解决?

答:在临界段中使用wait()方法,使执行该方法的线程等待,并允许其他线程使用这个

临界段。wait()方法常用以下两种格式:

wait(),让线程一直等待,直到被notify()或notifyAll()方法唤醒。

wait(long timeout),让线程等待到被唤醒,或经过指定时间后结束等待。

当线程使用完临界段后,用notify()方法通知由于想使用这个临界段而处于等待的线程

结束等待。notify()方法只是通知第一个处于等待的线程。如果某个线程在使用完临界段方

法后,其他早先等待的线程都可结束等待,重新竞争CPU,则可以notifyAll()方法。

8.6模拟排队买票,球票5元,购票者持有5,10,20,50元的,售票员手里开

始没有零钱。

程序运行结果:

主窗体源文件:

import .*;

import .*;

import .*;

/**

* 8.6 线程实现,购票规则,由于我想的算法太过复杂,只写到50元面值的

* @author 段智敏

*/

public class BuyTicketFrame extends JFrame implements ActionListener,

Runnable

{

private static final long serialVersionUID = 1L;

private Conductor lady;

private int array[] = { 10, 10, 5, 20, 50, 5, 5, 5, 5, 5, 5, 10, 20,

10, 5, 10, 20, 5 };

private int number = ;

100

private Thread thread[] = new Thread[number];

static JTextArea text;

private JButton begin_button, replay_button;

private JPanel panel;

public BuyTicketFrame()

{

super("第八章,第六题,线程模拟购票");

lady = new Conductor(15);

text = new JTextArea();

panel = new JPanel();

begin_button = new JButton("开始买票");

replay_button = new JButton("重新开始");

for (int i = 0; i < ; i++)

thread[i] = new Thread(this);

begin_ionListener(this);

replay_ionListener(this);

out(new FlowLayout());

(begin_button);

(replay_button);

(panel, );

(new JScrollPane(text), );

e(1000, 700);

ible(true);

te();

dowListener(new WindowAdapter()// 窗口监视器

{

public void windowClosing(WindowEvent e)

{

(0);

}

});

}

public void actionPerformed(ActionEvent e)

{

if (rce() == begin_button)// 线程开始

{

t("********" + number + "个人排队买票,共" +

ketAmount() + "张票,开始卖票:n");

try

{

for (int i = 0; i < ; i++)

{

thread[i].start();

if (thread[i].isAlive())

(" " + (i + 1) + "线程开始n");

}

begin_eground();

}

catch( IllegalThreadStateException ee )

{

("error:重复启动线程" + ng());

}

// 检查线程是否结束

while (true)

{

int n = 0;

for (int i = 0; i < ; i++)

{

101

}

if (thread[i].isAlive())

break;

else

n++;

}

if (n == )

break;

}

begin_eground();// 全部线程结束

("n全部线程结束,已经没有排队等待买票的了");

}

if (rce() == replay_button)

{

All();

new BuyTicketFrame();

}

}

public void run()

{

for (int i = 0; i < ; i++)

{

if (tThread() == thread[i])

(i + 1, array[i]);

}

}

public static void main(String args[])

{

new BuyTicketFrame();

}

售票员类源文件:

/**

* 售票员

* @author 段智敏

*/

class Conductor

{

/** 售票员开始持有的各种钞票的数量 */

private int five = 0, ten = 0, twenty = 0, fifty = 0;

/** 总的票数 */

private int ticket_amount;

/**

* 构造方法

* @param number - 票的初始数

*/

public Conductor(int number)

{

_amount = number;

}

public int getTicketAmount()

{

return ticket_amount;

}

102

/**

* 买票规则方法

*/

public synchronized void rule(int index, int money)

{

if (ticket_amount <= 0)

{

(index + "************售票结束

**********n");

return;

}

if (money == 5)

fiveGive(index);

if (money == 10)

tenGive(index);

if (money == 20)

twentyGive(index);

if (money == 50)

fiftyGive(index);

.append("--------------------------------------------------------

-----------------------");

("剩余票数:" + ticket_amount + "张:¥:

5元:" + five + "张;10元:" + ten

+ "张;20元:" + twenty + "张;50元:" + fifty + "张n");

notifyAll();// 唤醒所以线程

}

public void fiveGive(int index)

{

if (ticket_amount <= 0)

{

(index + "************售票结束

**********n");

return;

}

else

{

five++;

ticket_amount--;

("第" + index + "个,5快的,钱正好,

给你票n");

}

}

public void tenGive(int index)// 10元找钱规则

{

while (true)

{

if (five >= 1)

break;

else

{

("第" + index + "个,10元,找不

开,发...生...等...待...☆☆☆☆☆n");

try

{

103

wait();

}

catch( InterruptedException e )

{

}

}

}

if (ticket_amount <= 0)

{

(index + "************售票结束

**********n");

return;

}

else

{

ticket_amount--;

five--;

ten++;

("第" + index + "个,10元的,找你5

元的,给你票n");

}

}

public void twentyGive(int index)// 20元找钱规则

{

while (true)

{

if (((five >= 1 && ten >= 1) || five >= 3))// 20元的两种找钱

规则:3*5,10+5

break;// 跳出while循环,意味着有符合的规则

else

{

("第" + index + "个,20元,找不

开,发...生...等...待...☆☆☆☆☆n");

try

{

wait();

}

catch( InterruptedException e )

{

}

}

}

if (ticket_amount <= 0)

{

(index + "************售票结束

**********n");

return;

}

else if (ten >= 1 && five >= 1)// 20元找钱规则:10+5

{

ticket_amount--;

five--;

ten--;

twenty++;

("第" + index + "个,20元的,找你1

104

个5元,1个10块的,给你票n");

return;

}

else if (five >= 3)// 20元找钱规则:5*3

{

ticket_amount--;

five -= 3;

twenty++;

("第" + index + "个,20元的,找你3

个5元的,给你票n");

}

}

public void fiftyGive(int index)// 50元,找钱规则

{

while (true)

{

if ((twenty >= 2 && five >= 1) || (twenty >= 1 && ten >= 2 &&

five >= 1)

|| (twenty >= 1 && ten >= 1 && five >= 3) || (ten >=

4 && five >= 1)

|| (ten >= 3 && five >= 3) || (ten >= 2 && five >= 5)

|| (ten >= 1 && five >= 7) || (five >= 9))

break;// 50元的8种找钱方法

else

{

("第" + index + "个,50元,找不

开,发...生...等...待...☆☆☆☆☆n");

try

{

wait();

}

catch( InterruptedException e )

{

}

}

}

// 跳出while循环后,符合照片规则

if (ticket_amount <= 0)

{

(index + "************售票结束

**********n");

return;

}

// 先可20的先找,然后在10元的

else if (twenty >= 2 && five >= 1)// 50元找钱规则1:20*2+5

{

ticket_amount--;

five--;

twenty -= 2;

fifty++;

("第" + index + "个,50元的,找你2

个20,1个5元的,给你票n");

return;

}

else if (twenty >= 1 && ten >= 2 && five >= 1)// 50元找钱规则2:

20+10*2+5

105

{

ticket_amount--;

twenty--;

ten -= 2;

five--;

fifty++;

("第" + index + "个,50元的,找你1

个20,2个10,1个5元的,给你票n");

return;

}

else if (twenty >= 1 && ten >= 1 && five >= 3)// 50元找钱规则3:

20+10+5*3

{

ticket_amount--;

twenty--;

ten--;

five -= 3;

fifty++;

("第" + index + "个,50元的,找你1

个20,1个10,1个5元的,给你票n");

return;

}

else if (ten >= 4 && five >= 1)// 50元找钱规则4:10*4+5

{

ticket_amount--;

ten -= 4;

five -= 1;

fifty++;

("第" + index + "个,50元的,找你4

个10,1个5元的,给你票n");

return;

}

else if (ten >= 3 && five >= 3)// 50元找钱规则5:10*3+5*3

{

ticket_amount--;

ten -= 3;

five -= 3;

fifty++;

("第" + index + "个,50元的,找你3

个10,3个5元的,给你票n");

return;

}

else if (ten >= 2 && five >= 5)// 50元找钱规则6:10*2+5*5

{

ticket_amount--;

ten -= 2;

five -= 5;

fifty++;

("第" + index + "个,50元的,找你2

个10,5个5元的,给你票n");

return;

}

else if (ten >= 1 && five >= 7)// 50元找钱规则7:10+5*7

{

ticket_amount--;

ten--;

five -= 7;

fifty++;

("第" + index + "个,50元的,找你1

106

个10,7个5元的,给你票n");

return;

}

else if (five >= 9)// 50元找钱规则8:5*9

{

ticket_amount--;

five -= 9;

fifty++;

("第" + index + "个,50元的,找你9

个5元的,给你票n");

}

}

}

8.7修改例8.5程序,使一些暂时找不到零钱等待的顾客能按照先来先买的规则,

排队等待购买纪念品。

程序运行结果:

主窗口类:

import .*;

import .*;

import .*;

/**

* 排队买票,主窗口类

* @author 段智敏

*

*/

public class MainFrame extends JFrame implements ActionListener

{

private static final long serialVersionUID = 1L;

/** 19个顾客的信息,名字,和钱 */

private String name[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I",

"J", "K", "L", "M", "N",

"O", "P", "Q", "R", "S" };

private int moneies[] = { 10, 10, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5,

5, 10, 5, 10, 5, 5, 5 };

private Customer[] customer;

private SalesLady lady;

107

/** 显示信息的文本区,显示售票员信息,和队伍信息 */

private JTextArea text1, text2;

/** 开始按钮 */

private JButton start_button;

/** 布局用的panel */

private JPanel panel1, panel2;

public MainFrame()

{

super("多线程 - 排队 - 买票");

customer = new Customer[];

lady = new SalesLady();

text1 = new JTextArea();

text2 = new JTextArea();

start_button = new JButton("开始演示");

panel1 = new JPanel();

panel2 = new JPanel();

xtArea(text1, text2);

start_ionListener(this);

der(TitledBorder("信息栏"));

out(new GridLayout(1, 2, 10, 10));

(new JScrollPane(text1));

(new JScrollPane(text2));

(start_button);

nds(50, 50, 550, 400);

(panel1, );

(panel2, );

ible(true);

te();

dowListener(new WindowAdapter()

{

public void windowClosing(WindowEvent e)

{

(0);

}

});

}

public void actionPerformed(ActionEvent e)

{

start_bled(false);

();

for (int i = 0; i < ; i++)

{

customer[i] = new Customer(name[i], moneies[i], lady);// 创

建消费者

customer[i].start();

}

}

public static void main(String args[])

{

new MainFrame();

}

}

售货员类源文件:

import rea;

108

/**

* 售货员类

*/

public class SalesLady extends Thread

{

private int mem, five, ten; // 纪念品数,5、10元RMB张数

private LinkQueue queue;// 链队列

private boolean state;// 用来让线程结束的

private JTextArea text1, text2;

private int amount;// 用来确定线程的结束

public SalesLady(int length)

{

= length;

mem = 20;

five = 0;

ten = 0;

state = true;

queue = new LinkQueue();

}

/**

* 构造方法

* @param m - 纪念品数

* @param f - 5元数量

* @param t - 10元数量

* @param l - 人数

*/

public SalesLady(int m, int f, int t, int l)

{

= m;

= f;

= t;

= l;

state = true;

queue = new LinkQueue();

}

/**

* 排队,入队列

* @param obj

*/

public synchronized void stand_in_a_line(Object obj)

{

e(obj);

(ng() + "来排队了,此时队伍:" +

ueue() + "n");

}

public void run()

{

while (state)

{

if (amount == 0)

break;

if (!yQueue())

{

try

109

{

Customer cus = (Customer) ue();

(ng() + "在队头,所以去买票并出队,

此时队伍:" + ueue()

+ "n");

(ruleForSale(cus));

}

catch( Exception e )

{

tackTrace();

}

}

}

("售货员:没人排队了,我下班了");

}

/**

* 卖票规则方法

* @param num - 顾客号

* @param money - 顾客给的钱

* @return - 购买信息

*/

public String ruleForSale(Customer cust)

{

String message = "";

int money = ey();

String name = tomerName();

if (mem == 0)

{

state = false;

message = "售货员:对不起,纪念币已经卖完!n";// 结束方法

}

else if (money == 5)

{

mem--;

five++;

amount--;

message = "售货员:顾客-" + name + ",成功购买1个纪念品,你的钱正

好.n";

}

else if (money == 10)

{

if (five < 1)

{

stand_in_a_line(cust);

message = ("售货员:顾客-" + name + ",用10元买物品,没有零钱,

请去重新排队," + name + "很无奈的去排队了n");

}

else

{

mem--;

five--;

ten++;

amount--;

message = "售货员:顾客-" + name + ",成功购买1个纪念品,你给

我10块,我找你5块!n";

110

}

}

}

return message;

}

public void setJTextArea(JTextArea text1, JTextArea text2)

{

1 = text1;

2 = text2;

}

顾客类源文件:

/**

* 顾客类

*/

public class Customer extends Thread

{

private String name;

private int money;

private SalesLady lady;

public Customer(String name, int money, SalesLady lady)

{

super(name);

= name;

= money;

= lady;

}

/**

* 得到顾客排队序号

* @return - 序号

*/

public String getCustomerName()

{

return ;

}

/**

* 得到顾客付的钱数

* @return - 钱

*/

public int getMoney()

{

return ;

}

public String toString()

{

return ;

}

public void run()

{

try

{

_in_a_line(this);

(10);

}

111

}

catch( InterruptedException e )

{

}

}

链队列类源文件:

/**

* 队列的链式存储

* @author 段智敏

*/

public class LinkQueue

{

/** 队列头 */

private Node front;

/** 队列尾 */

private Node rear;

public LinkQueue()

{

Node p = new Node();

front = p;

rear = p;

}

/**

* 入队列操作

* @param obj - 要入队的数据

*/

public void enQueue(Object obj)

{

Node p = new Node(obj);// 数据位obj,next为null的节点

t(p);// 队尾的next为p,把p连接到队列上

= p;// p变成队尾

}

/**

* 出队列操作

* @return 返回以出队列的节点的数据

* @throws Exception

*/

public Object outQueue() throws Exception

{

if (isEmptyQueue())

throw new Exception("error:队列为空,不能操作!");

else

{

Object obj;

Node s = t();

obj = a();

t(t());// 删掉头结点后面的节点,所以front的

next 等于

// 他后面的节点的next

if (t() == null)// 如果此时front的下个节点为空,则

出队后,队列就空

rear = front;

return obj;

}

112

}

}

/**

* 判断队列是否为空

* @return 为空,返回真,不为空,返回假

*/

public boolean isEmptyQueue()

{

if (front == rear)

return true;

else

return false;

}

/**

* 得到队头元素

* @return 返回队头元素的数据

* @throws Exception

*/

public Object getHeadData() throws Exception

{

if (isEmptyQueue())

throw new Exception("error:队列为空,不能操作!");

else

{

return t().getData();

}

}

/**

* 得到队头的引用

* @return 返回队头元素的引用

* @throws Exception

*/

public Node getHeadNode() throws Exception

{

if (isEmptyQueue())

throw new Exception("error:队列为空,不能操作!");

else

{

return front;

}

}

/**

* 打印出队列的所有元素

*/

public String printQueue()

{

String result = "";

Node p = t();

while (p != null)

{

result += (a().toString() + " ");

p = t();

}

return result;

}

113

链式存储结点类源文件:

package 8_7;

/**

* 链式存储时候,用的结点类

*/

public class Node

{

/** 此结点的后继结点的引用 */

private Node next;

/** 此结点的数据 */

private Object data;

/**

* 无参数构造方法,后继引用和数据都为null

*/

public Node()

{

= null;

= null;

}

/**

* 直接设置此结点数据的构造方法

* @param obj - 该结点的数据

*/

public Node(Object obj)

{

= null;

= obj;

}

/**

* 同时设置该结点的后继结点,和数据

* @param obj - 该结点的数据

* @param next - 该结点的后继结点的引用

*/

public Node(Object obj, Node next)

{

= next;

= obj;

}

/**

* 设置后继结点的引用

* @param n - 该结点的后继结点

*/

public void setNext(Node n)

{

= n;

}

/**

* 得到其后继结点的引用

* @return 返回结点引用

*/

public Node getNext()

{

return next;

114

}

/**

* 设置其数据

* @param obj - 数据

*/

public void setData(Object obj)

{

= obj;

}

/**

* 得到数据,object类型

* @return 返回数据

*/

public Object getData()

{

return ;

}

/**

* 得到此数据的字符串形式

*/

public String toString()

{

return ng();

}

}

115

第九章 输入和输出流

9.2一个文本,一个按钮。在文本区中输入数据,点击按钮,将文本内容输出到

文件。文件通过文件保存对话框制定。

程序运行结果:

保存文件的源文件:

import .*;

import .*;

import .*;

import .*;

/**

* 9.2 一个文本,一个按钮。

* 在文本区中输入数据,点击按钮,将文本内容输出到文件。

* 文件通过文件保存对话框制定。

* @author 段智敏

*/

public class SaveFile extends JFrame implements ActionListener

{

private static final long serialVersionUID = 1L;// 序列化时为了保持版

本的兼容性

private JFileChooser fileChooser;// 文件选择对话框

private JPanel northPanel;// 布局用的

private JButton saveFileButton;// 保存按钮

private JLabel label;// 用来显示文件的绝对路径

private JTextArea textArea;// 文本框

public SaveFile()

{

super("第九章,第二题 - 保存文件");

label = new JLabel(" ");

fileChooser = new JFileChooser();

northPanel = new JPanel();

saveFileButton = new JButton("保存到文件");

textArea = new JTextArea();

eWrap(true);

116

ionListener(this);

(saveFileButton);

(northPanel, );

(new JScrollPane(textArea), );

(label, );

aultCloseOperation(_ON_CLOSE);

nds(50, 50, 500, 500);

ible(true);

te();

}

public void actionPerformed(ActionEvent e) // 监听器方法

{

if (rce() == saveFileButton)

{

int message = veDialog(this);

if (message == E_OPTION)

{

File file = ectedFile();

t("保存到:" + olutePath());// 在

label上显示这个文件的绝对路径

le(e());// 设置JFrame的title为文件

的名字

saveFile(file);

}

else

{

t("没有文件被选中");

}

}

}

/**

* 把文本区上的内容保存到指定文件上

* @param f - 保存到的文件对象

*/

public void saveFile(File f)

{

try

{

FileWriter file = new FileWriter(f);

BufferedWriter out = new BufferedWriter(file);

(t(), 0,

t().length());

();

}

catch( Exception e )

{

t("写文件发生错误");

}

}

public static void main(String[] args)

{

new SaveFile();

}

}

117

9.3在一个文件中,每行存的是整数,各行整数个数不等,要求读这个文件,然

后计算每行整数的和,并存到另一个文件中。

程序运行结果:

计算文件中的整数和源文件:

import .*;

import .*;

import .*;

import .*;

import .*;

/**

* 9.3 在一个文件中,每行存的是整数,各行整数个数不等,

* 要求读如这个文件,然后计算每行整数的和,并存到另一个文件中。

* @author 段智敏

*

*/

public class FileIntegerSum extends JFrame implements ActionListener

{

private static final long serialVersionUID = 1L;

private JButton buttonSave, buttonCount, buttonOpen;// 按钮:保存,计

算,保存

private JTextArea textArea;//文本区

private JLabel label;//显示当前文件的绝对路径的label

private JFileChooser filedialog;//文件选择对话框

private JPanel panel;//布局用的panel

private File file = null;//文件对象

public FileIntegerSum()

{

super("第九章,第三题 - 整数求和");

buttonOpen = new JButton("打开文件");

buttonSave = new JButton("保存到...");

buttonCount = new JButton("计算结果");

label = new JLabel(" ");

panel = new JPanel();

textArea = new JTextArea();

filedialog = new JFileChooser();

osableFileFilter(new MyFileFilter("txt"));

ionListener(this);

ionListener(this);

ionListener(this);// 给按钮加监控

(buttonOpen);

(buttonCount);

(buttonSave);// 把按钮添加到panel面板上

(panel, );

(new JScrollPane(textArea), );

118

(label, );

nds(50, 50, 500, 300);

te();

ible(true);

aultCloseOperation(_ON_CLOSE);

}

public void actionPerformed(ActionEvent e)

{

if (rce() == buttonOpen)

{

logTitle("打开");

int result = enDialog(this);

if (result == E_OPTION)

{

file = ectedFile();

t("" + olutePath());

readFiletoText(file);

}

else if (result == _OPTION)

t("你没有选择任何文件n");

}

if (rce() == buttonSave)

{

logTitle("另存为");

int result = veDialog(this);

if (result == E_OPTION)

{

file = ectedFile();

t("" + olutePath());

saveAsText(file);

}

else if (result == _OPTION)

{

t("你没有选择任何文件n");

}

}

if (rce() == buttonCount)

{

t(null);

if ( != null)

countResult(file);

}

}

/**

* 将指定的文件显示在文本区上

* @param file - 指定的文件

*/

public void readFiletoText(File file)

{

try

{

FileReader file_reader = new FileReader(file);

BufferedReader in = new BufferedReader(file_reader);

String ss = new String();

while ((ss = ne()) != null)

{

119

(ss + 'n');

}

();

}

catch( FileNotFoundException e2 )

{

t("文件没有找到n");

}

catch( IOException e3 )

{

tackTrace();

}

etPosition(0);

}

/**

* 将文本区内容保存到指定文件

* @param file - 指定的文件

*/

public void saveAsText(File file)

{

try

{

FileWriter file_writer = new FileWriter(file);

BufferedWriter out = new BufferedWriter(file_writer);

(t(), 0,

(t().length()));

();

();

}

catch( FileNotFoundException e2 )

{

t("文件没有找到n");

}

catch( IOException e3 )

{

}

}

/**

* 计算指定文件上,每行整数之和,并显示在文本区上

* @param file - 指定的文件

*/

public void countResult(File file)

{

try

{

FileReader file_reader = new FileReader(file);

BufferedReader in = new BufferedReader(file_reader);

String temp = new String();

while ((temp = ne()) != null)

{

int number = 0;

StringTokenizer token = new StringTokenizer(temp, " ,.");

while (eTokens())

{

number += nt(ken());

}

(temp + "---------相加结果是:" + number +

120

'n');

}

();

}

catch( Exception e2 )

{

t("error" + e2 + 'n');

}

}

public static void main(String args[])

{

new FileIntegerSum();

}

}

9.4在一个文本区中输入数据,把输入的数据分析成各个单词,然后排序显示到

第二个文本区中,并通过文件保存对话框保存到文件中。

程序运行结果:

源文件:

import .*;

import .*;

import .*;

import .*;

import .*;

import .*;

/**

* 9.4 在一个文本区中输入数据,把输入的数据分析成各个单词,

* 然后排序显示到第二个文本区中,并通过文件保存对话框保存到文件中.

* @author 段智敏

*/

public class SortString extends JFrame implements CaretListener,

ActionListener

{

private static final long serialVersionUID = 1L;

private JTextArea input_text;// 用于输入的文本区

private JTextArea showResult_text2;// 显示排序后的文本区

private JButton clear_button, save_button;// 按钮:清空,保存

private JFileChooser filedialog;// 文件选择对话框

private JLabel label;

private JPanel panel1, panel2;

public SortString()

121

{

super("第九章,第四题 - 排序");

filedialog = new JFileChooser();

input_text = new JTextArea(" ", 15, 30);

showResult_text2 = new JTextArea(" ", 15, 30);

clear_button = new JButton("清 空");

save_button = new JButton("保存到...");

panel1 = new JPanel();

panel2 = new JPanel();

label = new JLabel(" ");

input_eWrap(true);

showResult_table(false);

input_etListener(this);

clear_ionListener(this);

save_ionListener(this);

(clear_button);

(save_button);

(new JScrollPane(input_text));

(new JScrollPane(showResult_text2));

(panel1, );

(panel2, );

(label, );

nds(20, 20, 700, 400);

te();

ible(true);

aultCloseOperation(_ON_CLOSE);

}

public void caretUpdate(CaretEvent e)

{

String string = input_t();

StringTokenizer fenxi = new StringTokenizer(string, "

();:.,.,'n''t'");

int n = okens();

String arrayStr[] = new String[n];

for (int i = 0; i < n; i++)

{

String temp = ken();

arrayStr[i] = temp;

}

(arrayStr);// 排序

showResult_t(null);

for (int i = 0; i < ; i++)

{

showResult_(arrayStr[i] + "n");

}

}

public void actionPerformed(ActionEvent e)

{

if (rce() == clear_button)

{

input_t(null);

}

if (rce() == save_button)

{

logTitle("另存为");

int result = veDialog(this);

if (result == E_OPTION)

{

122

File file = ectedFile();

t("" + olutePath());

saveAsText(file);

}

}

}

/**

* 把文本区上的内容保存到指定文件上

* @param f - 保存到的文件对象

*/

public void saveAsText(File file)

{

try

{

FileWriter file_writer = new FileWriter(file);

BufferedWriter out = new BufferedWriter(file_writer);

(showResult_t(), 0,

(showResult_t().length()));

();

();

}

catch( FileNotFoundException e2 )

{

t("文件没有找到");

}

catch( IOException e3 )

{

tackTrace();

}

}

public static void main(String args[])

{

new SortString();

}

}

9.5在一个文本区中输入数据,将文本区中的数据存入文件中,在又用户指定的

序号,程序从文件中读取对应序号数据,输出到文本框中。

程序运行结果:

源文件:Work9_

import Layout;

123

import .*;

import .*;

import .*;

/**

* 9.5 在一个文本区中输入数据,将文本区中的数据存入文件中

* 在又用户指定的序号,程序从文件中读取对应序号数据,输出到文本框中。

* @author 段智敏

*/

public class Work9_5 extends JFrame implements ActionListener,

ItemListener

{

private static final long serialVersionUID = 1L;

private JButton buttonSave;//保存文件

private JComboBox combo;//组合框,用来选择指定序号

private JTextArea input_textArea;//文本区,输入数据

private JTextField show_textField;//显示数据的文本框

private JFileChooser filedialog;//文件选择对话框

private JLabel label;//显示当前文件的绝对路径

private JPanel panel;

private String stringArray[] = new String[100];

private File file;

public Work9_5()

{

super("第九章,第五题");

buttonSave = new JButton("保存到文件");

combo = new JComboBox();

panel = new JPanel();

label = new JLabel(" ");

input_textArea = new JTextArea();

show_textField = new JTextField(30);

filedialog = new JFileChooser();

input_eWrap(true);

ionListener(this);

mListener(this);

(buttonSave);

(combo);

(show_textField);// 把按钮,check添加到panel面板上

(panel, );

(new JScrollPane(input_textArea), );

(label, );

nds(50, 50, 600, 300);

te();

ible(true);

aultCloseOperation(_ON_CLOSE);

}

public void actionPerformed(ActionEvent e)

{

if (rce() == buttonSave)

{

logTitle("另存为");

int result = veDialog(this);

if (result == E_OPTION)

{

file = ectedFile();

t("" + olutePath());

saveAsText(file);

124

}

else if (result == _OPTION)

{

t("你没有选择任何文件");

}

}

}

public void itemStateChanged(ItemEvent e)

{

int i = ectedIndex();

show_t(stringArray[i]);

n("" + i);

}

/**

* 把文本区上的内容保存到指定文件上

* @param f - 保存到的文件对象

*/

public void saveAsText(File file)

{

try

{

FileWriter file_writer = new FileWriter(file);

BufferedWriter out = new BufferedWriter(file_writer);

(input_t(), 0,

(input_t().length()));

();

();

readFile(file);

}

catch( FileNotFoundException e )

{

t("文件没有找到");

}

catch( IOException e )

{

tackTrace();

}

}

/**

* 按行读取文件,并保存,

* @param file - 指定的文件

*/

public void readFile(File file)

{

try

{

FileReader file_reader = new FileReader(file);

BufferedReader in = new BufferedReader(file_reader);

String ss = new String();

int i = 0;

while ((ss = ne()) != null)

{

m("第" + (i + 1) + "行");

stringArray[i] = ss;

i++;

}

show_t(stringArray[0]);

125

}

();

}

catch( FileNotFoundException e )

{

t("文件没有找到");

}

catch( IOException e )

{

tackTrace();

}

}

public static void main(String args[])

{

new Work9_5();

}

9.6一个文本区,一个按钮,点击按钮选择文件,然后又把文件中的内容输入到

文本区中。

程序运行结果:

打开文件原文件:

import Layout;

import .*;

import .*;

import .*;

/**

*9.6 一个文本区,一个按钮,点击按钮选择文件,然后又把文件中的内容输入到文本区中。


* @author 段智敏

*/

public class OpenAndShowFile extends JFrame implements ActionListener

{

private static final long serialVersionUID = 1L;// 序列化时为了保持版

本的兼容性

private JFileChooser fileChooser;// 文件选择对话框

private JPanel northPanel;// 用于布局的panel

private JButton openFileButton;// 打开文件的按钮

private JLabel label;// 用来显示文件绝对路径

private JTextArea textArea;// 文本区,来显示文件内容

private File file = null;

126

public OpenAndShowFile()

{

super("打开并显示文件");

label = new JLabel();

fileChooser = new JFileChooser();

northPanel = new JPanel();

openFileButton = new JButton("打开文件");

textArea = new JTextArea();

ionListener(this);

(openFileButton);

// 添加文件筛选,扩展内容,请保证MyFileFilter类的存在

osableFileFilter(new MyFileFilter("java"));

osableFileFilter(new MyFileFilter("txt"));

(northPanel, );

(new JScrollPane(textArea), );

(label, );

aultCloseOperation(_ON_CLOSE);

nds(50, 50, 500, 500);

ible(true);

te();

}

public void actionPerformed(ActionEvent e)

{

if (rce() == openFileButton)

{

int message = enDialog(this);

if (message == E_OPTION)

{

file = ectedFile();

if (file != null)

{

t(olutePath());

le(e());

readFiletoText(file);

}

}

else

{

t("没有文件被选中");

}

}

}

/**

* 显示制定文件到文本区

* @param f - 需要显示的文件引用

*/

public void readFiletoText(File f)

{

try

{

FileReader file = new FileReader(f);

BufferedReader in = new BufferedReader(file);

String s = new String();

t("");

while ((s = ne()) != null)

{

(s + "n");

}

();

127

}

}

catch( Exception e )

{

t("读文件发生错误");

}

}

public static void main(String args[])

{

new OpenAndShowFile();

}

以上题目中用到的文件筛选类原文件:

import ;

import lter;

/**

* 文件筛选类

* @author 段智敏

*/

public class MyFileFilter extends FileFilter

{

/**需要显示的文件的后缀名*/

private String postfix;

public MyFileFilter(String t)

{

postfix = t;

}

/**重写父类方法*/

public boolean accept(File file)

{

if (ctory())

return true;

String fileName = e();

int index = dexOf('.');

if (index > 0 && index < () - 1)

{

String extension = ing(index +

1).toLowerCase();

if ((postfix))

return true;

}

return false;

}

/**显示在文件类型上的文字*/

public String getDescription()

{

return "*." + postfix + "文件";

}

}

128

第十章 网络与数据库编程基础

10.1程序中,用何种对象存储IP地址和域名?

答:用InetAddress类的对象

10.2用代码示意程序获取域名和IP地址的方法。

答:

Import .*;

Class Example10_1{

Public static void main(String args[]){

Try{ //以下代码通过域名建立InetAddress对象:

InetAddress addr = ame();

String domainName = tName();//获得主机名

String IPName = tAddress();//获得IP地址

n(domainName);

n(IPName);

}

catch(UnknownHostException e){

tackTrace();

}

}

}

10.3URL的作用是什么?

答:一个URL对象可以表示一个网络资源。程序利用URL对象能实现Internet寻址、网络

资源的定位连接、在客户机与服务器之间直接访问等。

10.4URLConnection对象的作用是什么?

答:要接收和发关信息还要用URLConnection类,程序获得一个URLConnection对象,相

当于完成对指定URL的一个HTTP连接。

10.5由代码示意由网址读取网页内容的过程。

答:

public void readByURL(String urlName){

try{

URL url = new URL(urlName);//由网址创建URL对象

URLConnection tc = nnectin();//获得URLConnection对象

t();//设置网络连接

129

InptStreamReader in = new InputStreamReader(utStream());

BufferedReader dis = new BufferedReader(in);//采用缓冲式输入

String inline;

while((inline = ne())!=null){

(inline +”n”);

}

();//网上资源使用结束后,数据流及时关闭

}catch(MalformedURLException e){tackTrace();}

catch(IOException e){tacktrace();}

/*访问网上资源可能产生MalformedURLException和IOException异常*/

}

10.6网络编程可分哪些层次?

答:主机/终端模式;客户机/服务器(Client/Server,简称C/S)模式;浏览器/服务

器模式。

10.7分别说出socket连接和serverSocket连接的方法。

答:Server : 创建 ServerSocket对象监听,等待并接收Client的请求 ,利用返回

Socket对象与Client通信,关闭Socket,关闭监听

Client: 创建 Socket对象向Server请求,利用此Socket对象与Server通信,关闭Socket

结束与通信。

10.8说出java程序与数据库连接的方法。

答:(1) 使用JDBC-ODBC桥接器与数据连接。 (2) 用纯Java的JDBC驱动程序实现与数据

库连接

10.9 Connection对象的作用是什么?

答:Connection对象是用来表示数据库连接的对象,Java程序对数据库的操作都在这种

对象上进行。

10.10 ResultSet对象的作用是什么?

答:ResultSet对象实际上是一个由查询结果数据的表,是一个管式数据集,由统一形

式的数据行组成,一行对应一条查询记录。在ResultSet对象中隐含着一个游标,一次只能

获得游标当前所指的数据行,用next方法可取下一个数据行。

10.11如何获得可滚动结果集?

答:程序要获得一个可滚动结果集,只要在获得SQL的语句对象时,增加指定结果集的

两个参数即可。例如,以下代码:

Statement stmt = Statement(type,concurrency);

ResultSet rs = eQuery(SQL语句)

130

语句对象stmt的SQL查询就能得到相应类型的结果集。

int 型参数type决定可滚动集的滚动方式:

_FORWORD_ONLY,结果集的游标只能向下滚动。

_SCROLL_INSENSITIVE,游标可上下移动,当数据库变化时,当前结果集

不变。

ResultSet. TYPE_SCROLL_SENSITIVE,游标可上下移动,当数据库变化时,当前结果集

同步改变。

int 型参数concurrency决定数据库是否与可滚动集同步更新?

_READ_ONLY,不能用结果集更新数据库中的表。

_UPDATETABLE,能用结果集更新数据库中的表。

10.12说出实现数据库查询的方法。

答:利用 Connection对象的createStatement方法建立Statement对象,利用Statement

对象的executeQuery()方法执行SQL查询语句进行查询,返回结果集,再利用getXXXX()的方

法从结果集中读取数据。

131


本文标签: 文件 数据 对象 线程 文本