input sth into a file

package key.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

public class Stringtest {
public static void main(String args[]) throws Exception{
String path="/E:/eclipse-jee-galileo-SR2-win32/eclipse/";
StringBuffer input=new StringBuffer();
input.append("set path=\""+path.substring(1)+"jdk\"\r");
input.append("classpath=\""+path.substring(1)+"jdk\\bin\"\r");
input.append("JAVA_HOME=\""+path.substring(1)+"jdk\"\r");
input.append("CATALINA_HOME=\""+path.substring(1)+"apache-tomcat-6.0.29\"\r");

System.out.println(input.toString());

File file=new File("E:\\eclipse-jee-galileo-SR2-win32\\eclipse\\plugins\\apache-tomcat-6.0.29\\bin\\abc.bat");
insertStringInFile(file,1,input.toString());

}
}
public static  void insertStringInFile(File inFile, int lineno, String lineToBeInserted)
    throws Exception {
  // 临时文件
  File outFile = File.createTempFile("name", ".tmp");

  // 输入
  FileInputStream fis = new FileInputStream(inFile);
  BufferedReader in = new BufferedReader(new InputStreamReader(fis));

  // 输出
  FileOutputStream fos = new FileOutputStream(outFile);
  PrintWriter out = new PrintWriter(fos);

  // 保存一行数据
  String thisLine;
  // 行号从1开始
  int i = 1;
  while ((thisLine = in.readLine()) != null) {
    // 如果行号等于目标行,则输出要插入的数据
    if (i == lineno) {
      out.println(lineToBeInserted);
    }
    // 输出读取到的数据
    out.println(thisLine);
    // 行号增加
    i++;
  }
  out.flush();
  out.close();
  in.close();

  // 删除原始文件
  inFile.delete();
  // 把临时文件改名为原文件名
  outFile.renameTo(inFile);
}
}

你可能感兴趣的:(java,apache,eclipse,jdk,tomcat)