ApiOperation(value = "下载文件", httpMethod = "GET", notes = "downloadFile", response = String.class)
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "zabbix.txt";// 设置文件名
if (fileName != null) {
//设置文件路径
// String realPath = "D://zabbix_agentd.conf";
String realPath = "D:" + File.separator + "zabbix_agentd.conf";
File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
InetAddress addr = InetAddress.getLocalHost();
String ip=addr.getHostAddress(); //获取本机ip
replacTextContent(ip);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
/**
* 替换文本文件中的 指定字符串
* @param path
* @throws IOException
*/
public void replacTextContent(String ip){
try {
File file = new File("D:zabbix_agentd.conf");
String content = FileUtils.readFileToString(file, "utf-8");
//原有的内容
String srcStr = "Hostname=192.168.1.177";
//要替换的内容
String replaceStr ="Hostname"+ ip;
// 读
FileReader in = new FileReader(content);
BufferedReader bufIn = new BufferedReader(in);
// 内存流, 作为临时流
CharArrayWriter tempStream = new CharArrayWriter();
// 替换
String line = null;
while ( (line = bufIn.readLine()) != null) {
// 替换每行中, 符合条件的字符串
line = line.replaceAll(srcStr, replaceStr);
// 将该行写入内存
tempStream.write(line);
// 添加换行符
tempStream.append(System.getProperty("line.separator"));
}
// 关闭 输入流
bufIn.close();
// 将内存中的流 写入 文件
FileWriter out = new FileWriter(file);
tempStream.writeTo(out);
out.close();
}catch (Exception e) {
e.printStackTrace();
}
}