您的位置:首页 > 编程语言 > Java开发

使用java程序修改本地文件部分内容

2017-09-15 11:03 369 查看
/**
* @author zhangjunyao
* 修改本地文件内容
*/
public class AppModifyTest {

/**
* 读取文件内容
*
* @param filePath
* @return
*/
public String read(String filePath) {
BufferedReader br = null;
String line = null;
StringBuffer buf = new StringBuffer();

try {
// 根据文件路径创建缓冲输入流
br = new BufferedReader(new FileReader(filePath));

// 循环读取文件的每一行, 对需要修改的行进行修改, 放入缓冲对象中
while ((line = br.readLine()) != null) {
// 此处根据实际需要修改某些行的内容
if (line.startsWith("    upstream localhosttest {")) {
buf.append(line).append("server 127.0.0.1:7001;");
}
else if (line.startsWith("b")) {
buf.append(line).append(" start with b");
}
// 如果不用修改, 则按原来的内容回写
else {
buf.append(line);
}
buf.append(System.getProperty("line.separator"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
}
}
}
return buf.toString();
}

/**
* 将内容回写到文件中
*
* @param filePath
* @param content
*/
public void write(String filePath, String content) {
BufferedWriter bw = null;

try {
// 根据文件路径创建缓冲输出流
bw = new BufferedWriter(new FileWriter(filePath));
// 将内容写入文件中
bw.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
bw = null;
}
}
}
}

/**
* 主方法
*/
public static void main(String[] args) {
String filePath = "D:/nginx-1.12.1/nginx-1.12.1/conf/nginx.conf"; // 文件路径
FileModifyTest2 obj = new FileModifyTest2();
for(int i=0;i<10;i++){
obj.write(filePath, obj.read(filePath)); // 读取修改文件
}

}

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐