用java读取nginx.conf内容,保留原有格式写入到nginx2.conf,读取和写入分成两个方法,并防止乱码
时间: 2023-01-11 13:55:36 浏览: 274
下面是代码示例:
```
// 读取 nginx.conf 的内容并保留原有格式
public String readNginxConf() {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("nginx.conf"), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
// 将读取到的内容写入到 nginx2.conf 中
public void writeNginxConf(String content) {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("nginx2.conf"), StandardCharsets.UTF_8))) {
bw.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
```
注意:使用 `InputStreamReader` 和 `OutputStreamWriter` 时需要指定字符集,这样可以避免乱码问题。
阅读全文