我的文件如下。
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实现相同功能的指示。
答案 0 :(得分:0)
此方法将 CharSequence 添加到文件的开头,这是我认为您正在寻找的。 p>
/**
* 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");
}