這是為了熟悉文件操作而寫的文件搜索器
?
?
?
1.實(shí)現(xiàn)文件搜索的具體實(shí)現(xiàn)
package 文件搜索器; import java.io.File; /** * 指定目錄下的給定關(guān)鍵字的文件搜索 * * @author d.s */ public class fileSearcher { /** * 搜索方法 * * @param path給定的目錄 * @param key關(guān)鍵字 */ public void Search(String path, String key) { File file = new File(path); // 如果給的路徑正確 if (file.exists()) { if (file.isDirectory()) { if(file.getName().indexOf(key) != -1) //關(guān)鍵字在文件夾名中存在的話. System.out.println(file.getAbsolutePath()); File f[] = file.listFiles(); for(int i = 0;i<f.length;i++){ //遞歸搜索. Search(f[i].getAbsolutePath(),key); } } if(file.isFile()){ if(file.getName().indexOf(key) != -1) //關(guān)鍵字在文件名中存在的話. System.out.println(file.getAbsolutePath()); } } } }
?
?
2.界面
package 文件搜索器; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; /** * 界面 * @author d.s * */ public class fileSearcherUI extends JFrame{ public static void main(String args[]){ fileSearcherUI ui = new fileSearcherUI(); ui.showUI(); } public void showUI(){ this.setTitle("fileSearcher"); this.setSize(300,120); JLabel jl = new JLabel("指定目錄:"); JTextField jf = new JTextField(20); JLabel jl1 = new JLabel(" 關(guān)鍵字:"); JTextField jf1 = new JTextField(20); //添加組建 this.add(jl); this.add(jf); this.add(jl1); this.add(jf1); JButton but = new JButton("搜索"); this.add(but); this.setLayout(new FlowLayout());//流體式布局 this.setLocationRelativeTo(null);//居中顯示 this.setResizable(false);//不可改變大小 this.setDefaultCloseOperation(EXIT_ON_CLOSE);//關(guān)閉時(shí)退出 this.setVisible(true);//顯示界面 ActionListenerImpl l = new ActionListenerImpl(jf, jf1); but.addActionListener(l); } }
?
?
?
3.監(jiān)聽器
package 文件搜索器; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JTextField; public class ActionListenerImpl implements ActionListener{ private JTextField jf; private JTextField jf1; //獲取文件指定的路徑和關(guān)鍵字 public ActionListenerImpl(JTextField jf, JTextField jf1){ this.jf = jf; this.jf1 = jf1; } public void actionPerformed(ActionEvent e) { fileSearcher fs = new fileSearcher(); fs.Search(jf.getText(), jf1.getText()); } }
?
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
