2011-06-25 30 views
0

我有如下文件。如何将字符串前缀到文件的起始位置的文件中?

rule "IC-86" 
    agenda-group "commonATSP" 
    dialect "mvel" 
    when 
     eval($count > 10) 
    then 
     modify($attribute){ $imageVersion,$attributes.get(),imageName }; 
end 

我需要在文件的顶部为下面提到的字符串加上前缀。

import java.lang.Exception; 

输出应该如下所示。

import java.lang.Exception; 
    rule "IC-86" 
     agenda-group "commonATSP" 
     dialect "mvel" 
     when 
      eval($count > 10) 
     then 
      modify($attribute){ $imageVersion,$attributes.get(),imageName }; 
    end 

请给我提供一些使用Java实现相同的指针。

+1

你居然是Drools的的维护者文件或您是从另一方得到它,不能修改呢?换句话说,你是否有理由不能修改DRL以包含导入? – Perception

+0

为什么java?它可以简单地用单个bash行来实现 – amit

+0

我在生成drl之后从BRL生成drl文件,我需要添加相应的导入。 – thogadam

回答

0

此方法将一个CharSequence作为我想要查找的文件的开头。

/** 
* Prepends a string value to the beginning of a file 
* @param prepend The prepended value 
* @param addEol If true, appends an EOL character to the prepend 
* @param fileName The file name to prepend to 
*/ 
public static void prependToFile(CharSequence prepend, boolean addEol, String fileName) { 
    if(prepend==null) throw new IllegalArgumentException("Passed prepend was null", new Throwable()); 
    if(fileName==null) throw new IllegalArgumentException("Passed fileName was null", new Throwable()); 
    File f = new File(fileName); 
    if(!f.exists() || !f.canRead() || !f.canWrite()) throw new IllegalArgumentException("The file [" + fileName + "] is not accessible", new Throwable()); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    FileInputStream fis = null; 
    BufferedInputStream bis = null; 
    FileOutputStream fos = null; 
    BufferedOutputStream bos = null; 
    byte[] buffer = new byte[8096]; 
    int bytesRead = 0; 
    try { 
     baos.write(prepend.toString().getBytes()); 
     if(addEol) { 
      baos.write(System.getProperty("line.separator", "\n").getBytes()); 
     } 
     fis = new FileInputStream(f); 
     bis = new BufferedInputStream(fis); 
     while((bytesRead = bis.read(buffer)) != -1) { 
      baos.write(buffer, 0, bytesRead); 
     } 
     bis.close(); bis = null; 
     fis.close(); fis = null; 
     fos = new FileOutputStream(f, false); 
     bos = new BufferedOutputStream(fos); 
     bos.write(baos.toByteArray());   
     bos.close();    
    } catch (Exception e) { 
     throw new RuntimeException("Failed to prepend to file [" + fileName + "]", e); 
    } finally { 
     if(bis!=null) try { bis.close(); } catch (Exception e) {} 
     if(fis!=null) try { fis.close(); } catch (Exception e) {} 
     if(bos!=null) try { bos.close(); } catch (Exception e) {} 
     if(fos!=null) try { fos.close(); } catch (Exception e) {}      
    }  
} 

例子:

public static void main(String[] args) { 
    prependToFile("import java.lang.Exception;", true, "/tmp/rule.txt"); 
} 
相关问题