java文件读写操作的一个简单例子

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
public class coin extends JFrame implements ActionListener {
// 代码中涉及的异常处理自己看情况添加即可 包名更换成自己的 创建的 ceshi.txt 在自己的java项目中的scr文件夹,点击刷新即可看见
private JTextArea jTextArea = new JTextArea(15, 15);
private JButton jButton = new JButton("读取");
private JButton jButton2 = new JButton("写入");
public coin() {
JFrame jFrame = new JFrame("文件读写");
jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
jFrame.setLayout(new FlowLayout());
jFrame.setSize(300, 200);
jButton.addActionListener(this);
jButton2.addActionListener(this);
jFrame.add(jTextArea);
jFrame.add(jButton);
jFrame.add(jButton2);
jFrame.setVisible(true);
}
// 读取文件
public void readfile() throws IOException {
File file = new File("ceshi.txt");// 创建文件
try {
InputStream is = new FileInputStream(file);// 创建输入流
byte[] buffer = new byte[200];
while (is.read(buffer) != -1) {
String string = new String(buffer);
jTextArea.setText(string);
}
is.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
// 写入文件
public void writefile() throws IOException {
File file = new File("ceshi.txt");
try {
OutputStream os = new FileOutputStream(file, true);// true是追加写入 默认不追加
String string = jTextArea.getText().toString();
byte[] buffer = string.getBytes();// 将字符串 转换成byte数组
os.write(buffer);
os.close();
} catch (FileNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} //
}
// 按钮点击事件实现
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
if (e.getSource() == jButton) {
try {
readfile();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
} else if (e.getSource() == jButton2) {
try {
writefile();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
public static void main(String args[]) {
new coin();
}
}

0%