欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java逐行修改文件内容

程序员文章站 2022-04-24 12:14:00
...

**

Java逐行修改文件内容

**

    File _file = new File(iniPath);
	byte[] fileContext = new byte[(int) _file.length()];
	FileInputStream in = null;
	PrintWriter out = null;
	try {
	    in = new FileInputStream(_file);
	    in.read(fileContext);
	    String str = new String(fileContext,"utf-8");
	    String[] content = str.split("\r\n");
	    String newStr = new String();
	    for(String arg : content){
		if(arg.contains("Install")){
		    arg = arg.replace(arg, "InstallTime="+(int)(System.currentTimeMillis() / 1000)+"");
		}else if(arg.contains("Last")){
		    arg = arg.replace(arg, "LastLoading="+(int)(System.currentTimeMillis() / 1000)+"");
		}
		newStr += arg+"\r\n";
		Thread.sleep(100);
	    }
	    out = new PrintWriter(_file);
	    out.write(newStr);
	} catch (IOException | InterruptedException e1) {
	    return false;
	} finally{
	    try {
		out.flush();
		out.close();
		in.close();
	    } catch (IOException e) {
		return false;
	    }
	}