通过java修改文件内容

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class Getclasspath {
	/*获取当前项目根路径
	 * */
	public static  final String rootpath = System.getProperty("user.dir");
	/* 文件内容替换
	   filePath 文件路径
	   oldstr   要修改的字符串
	   newStr   修改后的字符串*/
	private static void autoReplace(String filePath, String oldstr, String newStr) {
		File file = new File(filePath);
		Long fileLength = file.length();
		byte[] fileContext = new byte[fileLength.intValue()];
		FileInputStream in = null;
		PrintWriter out = null;
		try {
			in = new FileInputStream(filePath);
			in.read(fileContext);
			// 防止中文乱码
			String str = new String(fileContext, "GBK");
			str = str.replace(oldstr, newStr);
			out = new PrintWriter(filePath);
			out.write(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
	}
	public static void runReplace(){
		autoReplace(rootpath+"\\..\\jar\\application.yml", "com/jy/pdm/mapper/", rootpath);
		autoReplace(rootpath+"\\..\\nginx\\conf\\nginx.conf", "/home/ftp/", rootpath);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		runReplace();
		System.out.println("完成!");
	}

}

你可能感兴趣的:(java)