搜索、替换文本

      最近我的Tomcat老是输出java/1.4.2_11,也不知道哪里输出的,由于文件很多如果一个一个找很费时间。就写了个java下文件搜索的小程序,因该有用的着的:)。文件保存每次会覆盖结果,如果想要每次的都保存,可以用BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile,true));构造输出流就不会覆盖上一次的结果了。

下面是源码:

 

package  common.fileoperate;
import  java.io. * ;

public   class  SearchFile {
 
private String path;
private int size;
private boolean force = false;
private String fileLine = null;
private String searchStr = null;
private BufferedReader br;
private BufferedWriter bw;
private String outputFileName;
private File outputFile;
private int currentPathIndex;

public SearchFile(){
 
if(searchStr == null)
  searchStr 
= "System.out.println";
 
if(outputFileName == null)
  outputFileName 
= "SearchFileOutput.txt";
 outputFile 
= new File(outputFileName);
}


//输出文件名
public void setOutputFileName(String outputFileName){
 
this.outputFileName = outputFileName;
}

public String getOutputFileName(){
 
return outputFileName;
}


//搜索字符串
public void setSearchStr(String searchStr){
 
this.searchStr = searchStr;
}

public String getSearchStr(){
 
return searchStr;
}



//搜索单个路径
public synchronized void searchSinglePath(String path)
{
File filePath 
= new File(path);
//System.out.println(filePath);
File[] readFile = filePath.listFiles();

//System.out.println(filePath.getAbsolutePath());
if(readFile == null){
 System.out.println(
"Readed File is null!!! Path: "+filePath.toURI());
 
return;
}

//System.out.println(readFile.length);
for(int i=0;i<readFile.length;i++){
//ext是图片的格式 gif jpeg 或png
File F = readFile[i];

double Ratio=0.0;
String fileName 
= F.getPath().toLowerCase();
int pos = fileName.lastIndexOf(".");
if(pos == -1){
 
continue;
}

String ext 
= fileName.substring(pos+1,fileName.length());
String prefixName 
= fileName.substring(0,pos);
//System.out.println(prefixName);
//System.out.println("fileName: "+fileName);
//System.out.println("fileName: "+fileName);
//System.out.println("filePath.toURI(): "+filePath.toURI());
//如果不是文件则不执行
if (!F.isFile())
continue;
try {
 br 
= new BufferedReader(new FileReader(F));
 
if(bw == null)
  bw 
= new BufferedWriter(new FileWriter(outputFile));
 
int j=0;
 
while((fileLine = br.readLine()) != null){
  j
++;
  
if(fileLine.toLowerCase().indexOf(searchStr.toLowerCase()) != -1){
   String beWrite 
= "文件名称: "+fileName+" ,第"+j+"行, "+"内容: "+fileLine+" ";
   bw.write(beWrite);
  }
                 
 }

 bw.flush();
}
catch (Exception ex) {
 System.out.println(
"error: fileName: "+fileName);
 ex.printStackTrace();
}
 
}

}


public void searchFile(String path)
{
File filePath 
= new File(path);
//System.out.println(filePath);
File[] readFile = filePath.listFiles();

//System.out.println(filePath.getAbsolutePath());
if(readFile == null){
 System.out.println(
"Readed File is null!!! Path: "+filePath.toURI());
 
return;
}

 searchSinglePath(path); 
 
//System.out.println(readFile.length);
 for(int i=currentPathIndex;i<readFile.length;i++){
  File F 
= readFile[i];
  
if(F.isDirectory()){
   currentPathIndex 
= i;
   System.out.println(
"fileCatalog: "+F.getPath());
   searchFile(F.getPath());   
  }

 }


}



public static void main(String[] args){

 SearchFile sf 
= new SearchFile();
 sf.setOutputFileName(
"SearchFileOutput.txt");
 sf.setSearchStr(
"System.out.println");
 sf.searchFile(
"E:/tomcat5/webapps/ROOT");

}

}


 

 

最近修改为图形界面,加了替换功能:

SearchFile.java

 

package  com.ytcen.fileoperate;
import  java.io. * ;
import  javax.swing. * ;
import  java.awt. * ;
import  java.awt.event. * ;

public   class  SearchFile  extends  JPanel  implements  ActionListener  {
    
private String path;
private int size;
private boolean force = false;
private String fileLine = null;
private String searchStr = null;
private BufferedReader br;//读取文件缓冲
private BufferedWriter bw;//写结果文件缓冲
private BufferedWriter bwReplace;//替换文件缓冲
private String outputFileName;
private File outputFile;
private File tmpFile;
private int currentPathIndex;
private JPanel jpNorth;//打开,查找,替换3个功能的面板
private JScrollPane jspSouth;//显示结果面板
private JPanel jpComp;//总面板
private JFileChooser jfc;
private JTextField jtfOpen;
private JTextField jtfFind;
private JTextField jtfReplace;
private JLabel jlOpen;
private JLabel jlFind;
private JLabel jlReplace;
private JButton jbOpen;
private JButton jbFind;
private JButton jbReplace;
private JTextArea jtaResult;


public SearchFile(){
    
if(searchStr == null)
        searchStr 
= "System.out.println";
    
if(outputFileName == null)
        outputFileName 
= "SearchFileOutput.txt";
    outputFile 
= new File(outputFileName);
    initPanel();        
}


public void initPanel(){
    jpComp 
= new JPanel(new BorderLayout());
    jpNorth 
= new JPanel(new GridBagLayout());
    jspSouth 
= new JScrollPane();
    
    jfc 
= new JFileChooser("C:/");
      jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      
    jlOpen 
= new JLabel("查找目录:");
    jtfOpen 
= new JTextField(30);
    jbOpen 
= new JButton("选择");
    
    jlFind 
= new JLabel("查找内容:");
    jtfFind 
= new JTextField(30);
    jbFind 
= new JButton("查找");
    jbFind.addActionListener(
this);
    
    jlReplace 
= new JLabel("替换内容:");
    jbReplace 
= new JButton("替换");
    jbReplace.addActionListener(
this);
    jtfReplace 
= new JTextField(30);
    
    GridBagConstraints gbc 
= new GridBagConstraints();
    gbc.gridx 
= 0 ;
    gbc.gridy 
= 0;
    gbc.gridwidth 
= 1;
    gbc.gridheight 
= 1;
    jbOpen.addActionListener(
this);
    jpNorth.add(jlOpen,gbc);
    gbc.gridx 
= 1;
    jpNorth.add(jtfOpen,gbc);
    gbc.gridx 
= 2;
    jpNorth.add(jbOpen,gbc);
    gbc.gridx 
= 0;
    gbc.gridy 
= 1;    
    jpNorth.add(jlFind,gbc);
    gbc.gridx 
=1;
    jpNorth.add(jtfFind,gbc);
    gbc.gridx 
= 2;
    jpNorth.add(jbFind,gbc);
    gbc.gridx 
= 0;
    gbc.gridy 
= 3;
    jpNorth.add(jlReplace,gbc);
    gbc.gridx 
= 1;
    jpNorth.add(jtfReplace,gbc);
    gbc.gridx 
= 2;
    jpNorth.add(jbReplace,gbc);    
    jtaResult 
= new JTextArea(null,14,50);
    jspSouth.setViewportView(jtaResult);
    jpComp.add(jpNorth,BorderLayout.NORTH);
    jpComp.add(jspSouth,BorderLayout.SOUTH);    
}


public JPanel getPanel(){
    
return jpComp;
}


//输出文件名
public void setOutputFileName(String outputFileName){
    
this.outputFileName = outputFileName;
}

public String getOutputFileName(){
    
return outputFileName;
}


//搜索字符串
public void setSearchStr(String searchStr){
    
this.searchStr = searchStr;
}

public String getSearchStr(){
    
return searchStr;
}



//搜索单个路径
public synchronized void searchSinglePath(String path,String replace)
{
File filePath 
= new File(path);
//System.out.println(filePath);
File[] readFile = filePath.listFiles();

//System.out.println(filePath.getAbsolutePath());
if(readFile == null){
    System.out.println(
"Readed File is null!!! Path: "+filePath.toURI());
    
return;
}


//System.out.println(readFile.length);
for(int i=0;i<readFile.length;i++){
//ext是图片的格式 gif jpeg 或png
File F = readFile[i];

double Ratio=0.0;
String fileName 
= F.getPath().toLowerCase();
int pos = fileName.lastIndexOf(".");
if(pos == -1){
    
continue;
}

String ext 
= fileName.substring(pos+1,fileName.length());
String prefixName 
= fileName.substring(0,pos);
//System.out.println(prefixName);
//System.out.println("fileName: "+fileName);
//System.out.println("fileName: "+fileName);
//System.out.println("filePath.toURI(): "+filePath.toURI());
//如果不是文件则不执行
if (!F.isFile())
continue;
try {
    br 
= new BufferedReader(new FileReader(F));
    
if(bw == null)
        bw 
= new BufferedWriter(new FileWriter(outputFile));
    
int j=0;
    
if(replace != null){
        tmpFile 
= new File(path+"/tmp.text");
        bwReplace 
= new BufferedWriter(new FileWriter(tmpFile));    
    }

    
while((fileLine = br.readLine()) != null){
        j
++;
        
if(fileLine.toLowerCase().indexOf(searchStr.toLowerCase()) != -1){
            String beWrite 
= "文件名称: "+fileName+" ,第"+j+"行, "+"内容: "+fileLine+" ";
            jtaResult.append(beWrite);
            bw.write(beWrite);
            
if(replace != null)
                fileLine 
= fileLine.replaceAll(searchStr,replace);
        }

        
if(replace != null)
            bwReplace.write(fileLine
+" ");                                                                    
    }

    br.close();
    bw.flush();
    
if(replace != null){
        bwReplace.flush();
        bwReplace.close();
        System.gc();
        F.delete();
        tmpFile.renameTo(F);
    }

}
catch (Exception ex) {
    System.out.println(
"error: fileName: "+fileName);
    ex.printStackTrace();
}
    
}

}


private void openDirectory(){
    
int result = jfc.showOpenDialog(new JFrame("选择文件夹"));
    
if(result == JFileChooser.APPROVE_OPTION){
        jtfOpen.setText(jfc.getSelectedFile().getAbsolutePath());
    }
    
}


public void searchFile(String path,String replace)
{
File filePath 
= new File(path);
//System.out.println(filePath);
File[] readFile = filePath.listFiles();

//System.out.println(filePath.getAbsolutePath());
if(readFile == null){
    System.out.println(
"Readed File is null!!! Path: "+filePath.toURI());
    
return;
}

    searchSinglePath(path,replace);    
    
//System.out.println(readFile.length);
    for(int i=currentPathIndex;i<readFile.length;i++){
        File F 
= readFile[i];
        
if(F.isDirectory()){
            currentPathIndex 
= i;
            System.out.println(
"fileCatalog: "+F.getPath());
            searchFile(F.getPath(),replace);            
        }

    }


}


private void findFile(){
    
if(jtfOpen.getText().equals("")){
        JOptionPane.showConfirmDialog(
this,"请选择要查找内容的文件夹","出错",JOptionPane.DEFAULT_OPTION);
        
return;
    }
else if(jtfFind.getText().equals("")){
        JOptionPane.showConfirmDialog(
this,"请输入要查找的内容","出错",JOptionPane.DEFAULT_OPTION);
        
return;
    }

    setSearchStr(jtfFind.getText());
    searchFile(jtfOpen.getText(),
null);    
}


private void replaceFile(){
    
if(jtfOpen.getText().equals("")){
        JOptionPane.showConfirmDialog(
this,"请选择要替换内容的文件夹","出错",JOptionPane.DEFAULT_OPTION);
        
return;
    }
else if(jtfFind.getText().equals("")){
        JOptionPane.showConfirmDialog(
this,"请输入要查找的内容","出错",JOptionPane.DEFAULT_OPTION);
        
return;
    }

    setSearchStr(jtfFind.getText());
    searchFile(jtfOpen.getText(),jtfReplace.getText());    
}

public void actionPerformed(ActionEvent e) {
        Object o 
= e.getSource();
        
if(o == jbOpen){
            openDirectory();
        }
else if(o == jbFind){
            jtaResult.setText(
"");
            findFile();
        }
else if(o == jbReplace){
            jtaResult.setText(
"");
            replaceFile();
        }

}



public static void main(String[] args){
     
new ShowPanel().inFrame(new SearchFile().getPanel(),600,400);
}

}

 

ShowPanel.java

 

package  com.ytcen.fileoperate;
import  java.awt. * ;
import  java.awt.event. * ;
import  javax.swing. * ;

public   class  ShowPanel  {
  
public static void 
  inFrame(JPanel jp, 
int width, int height) {
    String title 
= "文本速查";
    JFrame frame 
= new JFrame(title);
    frame.addWindowListener(
new WindowAdapter() {
      
public void windowClosing(WindowEvent e){
        System.exit(
0);
      }

    }
);
    frame.getContentPane().add(
      jp, BorderLayout.CENTER);
    frame.setSize(width, height);
    frame.setVisible(
true);
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值