【模仿】一个充满BUG的小程序
本来不想贴在这儿的,没什么技术含量。
关键一点就是复制按钮的实现了。用到了文件输入输出流和文件通道。(目前暂时不太清楚文件读写操作的原理,后续补上)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import java.awt.*; 2
3 import javax.swing.*;
4 import java.awt.event.*;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.nio.channels.FileChannel;
10
11 public class Test2 {
12
13 public static void main(String args[]) {
14 final JFrame jf = new JFrame("小程序");
15 jf.setSize(300,175);
16 jf.setResizable(false);
17 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18 jf.setLayout(new FlowLayout(FlowLayout.CENTER, 1, 5));
19 final JTextField jt1 = new JTextField(23);
20 final JTextField jt2=new JTextField(23);
21 JLabel jl1=new JLabel("原路径:");
22 JLabel jl2=new JLabel("目标路径:");
23
24 JButton jbMov = new JButton("剪切");
25 JButton jbCopy = new JButton("复制");
26 JButton jbDel = new JButton("删除");
27 jbMov.addActionListener(new ActionListener() {
28 public void actionPerformed(ActionEvent e) {
29 new File(jt1.getText()).renameTo(new File(jt2.getText()));
30
31 }
32
33 });
34 jbCopy.addActionListener(new ActionListener() {
35 public void actionPerformed(ActionEvent e) {
36 try {
37 fileCopy(jt1.getText(), jt2.getText());
38 } catch (IOException e1) {
39 // TODO Auto-generated catch block
40 e1.printStackTrace();
41 }
42 }
43 public void fileCopy(String source, String destination) throws IOException {
44 File f = new File(source);
45 File[] files = f.listFiles();
46 FileChannel in=null;
47 FileChannel out=null;
48 try {
49 for (File file : files) {
50 in = new FileInputStream(file).getChannel();
51 File outFile = new File(destination, file.getName());
52 out = new FileOutputStream(outFile).getChannel();
53 in.transferTo(0, in.size(), out);
54 }
55 } finally {
56 if (in != null) {
57 in.close();
58 }
59 if(out !=null){
60 out.close();
61 }
62 }
63 }
64 });
65 jbDel.addActionListener(new ActionListener() {
66 public void actionPerformed(ActionEvent e) {
67 new File(jt1.getText()).delete();
68 }
69 });
70 // jf.addComponentListener(new ComponentAdapter() {
71 //
72 // @Override
73 // public void componentResized(ComponentEvent e) {
74 //// 用于调整窗口大小,界面设计
75 // jf.setTitle(String.valueOf(jf.getSize().width) + " "
76 // + String.valueOf(jf.getSize().height));
77 // }
78 // });
79
80 jf.add(jl1);
81 jf.add(jt1);
82 jf.add(jl2);
83 jf.add(jt2);
84 jf.add(jbMov);
85 jf.add(jbCopy);
86 jf.add(jbDel);
87 // jf.pack();
88 jf.setVisible(true);
89
90 }
91
92
93 }
千里之行,始于足下
做自己热爱的工作,才能实现人生价值
热情在没有天赋的情况下,也能给予人巨大的力量