e81.java
4.0 KB
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
package com.tianbo.controller;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Win extends JFrame implements ActionListener//接口设置监听器
{
FileReader r_file;//字符文件输入流
FileWriter w_file;//字符文件输出流
BufferedReader buf_reader;//与FileReader类配合使用,将字符输入到缓冲区,使数据处理速度大大加快,提高读写的效率
BufferedWriter buf_writer;
JTextArea txt;
JButton btn1,btn2;
Win()
{
setSize(400,400);
setVisible(true);
txt = new JTextArea(10,10);
btn1 = new JButton("Read");
btn2 = new JButton("Write");
btn1.addActionListener(this);//建立监听器和事件源(按钮)之间的联系
btn2.addActionListener(this);
JPanel p = new JPanel();
add(txt,"Center");
add(p,"South");
p.setLayout(new FlowLayout());//设置窗体为浮动窗体
p.add(btn1);
p.add(btn2);
validate();//使窗体中的组件为可见
setDefaultCloseOperation(EXIT_ON_CLOSE);//设置关闭窗体,退出窗体
}
public void actionPerformed(ActionEvent e)
{
//当单击按钮对象btn时,按钮对象会产生一个ActionEvent事件,事件监听器监听到这个事件,把它作为实现ActionListener接口的actionPerformed方法的参数,在actionPerformed方法中处理动作事件。
if(e.getSource()==btn1)
{
readFile();
}
if(e.getSource()==btn2)
{
writeFile();
}
}
//读取文件
public void readFile()
{
String s;
try
{
File f=new File("C:\\A.txt");
r_file = new FileReader(f);//将文件f里面的内容给字符文件输入流
buf_reader = new BufferedReader(r_file);
}
catch(IOException ef)
{
System.out.print(ef);
}
try
{
int count =0;
double countK = 0;
String A = null;
while ((s = buf_reader.readLine())!=null)
{
String flag = s.substring(s.indexOf("/")+1,s.indexOf("K", s.indexOf("K")+1));
if(flag.contains("D")){
A=s.substring(s.indexOf("D")+1, s.indexOf("K", s.indexOf("K")+1));
}else if(flag.contains("S")){
A =s.substring(s.indexOf("S")+1, s.indexOf("K", s.indexOf("K")+1));
}
txt.append(s+'\n');
String K =s.substring(s.indexOf("K", s.indexOf("K")+1)+1,s.indexOf("M"));
count += Integer.parseInt(A);
countK += Double.parseDouble(K);
}
txt.append("总件数"+count);
txt.append("总重量"+countK);
}
catch(IOException er)
{
System.out.print(er);
}
}
public void writeFile()
{
try
{
w_file = new FileWriter("C:\\x.txt");
buf_writer = new BufferedWriter(w_file);
String str = txt.getText();
buf_writer.write(str,0,str.length());
buf_writer.flush();//一般情况下,writer方法向输出流写数据时,先把数据存放在缓冲区,这时缓冲区的数据不会自动写入输出流,只有当缓冲区满时,才会一次性将缓冲区的数据写入输出流,即写入文件。为了把尚未填满的缓冲区中的数据送出去,这时就要使用flush方法。
}
catch(IOException ew)
{
System.out.print(ew);
}
}
}
public class e81
{
public static void main(String args[])
{
Win w = new Win();
}
}