工具类Utils

本文汇总了多种实用的Java工具类,包括HTTP客户端工具、Excel导出工具、PDF操作工具、配置文件更新工具、服务器参数获取工具及远程SSH连接工具,旨在帮助开发者提高开发效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.HttpClientUtils

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>
package mirror.utils;


import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * @Author: hekaikai
 * @Date: 2020/11/16 10:57
 */
public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }


    public static String doPut(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http PUT请求
            HttpPut httpPut = new HttpPut(uri);

            // 执行请求
            response = httpclient.execute(httpPut);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doPut(String url){
         return doPut(url, null);
    }
}



2. ExportUtils(POI导出)

package com.casic.util;


import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class ExportUtils<T> {

	
	// 2007 版本以上 最大支持1048576行
		public  final static String  EXCEl_FILE_2007 = "2007";
		// 2003 版本 最大支持65536 行
		public  final static String  EXCEL_FILE_2003 = "2003";
		
		/**
		 * <p>
		 * 导出无头部标题行Excel <br>
		 * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
		 * </p>
		 * 
		 * @param title 表格标题
		 * @param dataset 数据集合
		 * @param out 输出流
		 * @param version 2003 或者 2007,不传时默认生成2003版本
		 */
		public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) {
			if(StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())){
				exportExcel2003(title, null, dataset, out, "yyyy-MM-dd HH:mm:ss");
			}else{
				exportExcel2007(title, null, dataset, out, "yyyy-MM-dd HH:mm:ss");
			}
		}
	 
		/**
		 * <p>
		 * 导出带有头部标题行的Excel <br>
		 * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
		 * </p>
		 * 
		 * @param title 表格标题
		 * @param headers 头部标题集合
		 * @param dataset 数据集合
		 * @param out 输出流
		 * @param version 2003 或者 2007,不传时默认生成2003版本
		 */
		public void exportExcel(String title,String[] headers, Collection<T> dataset, OutputStream out,String version) {
			if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
				exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss");
			}else{
				exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss");
			}
		}
	 
		/**
		 * <p>
		 * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
		 * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
		 * </p>
		 * 
		 * @param title
		 *            表格标题名
		 * @param headers
		 *            表格头部标题集合
		 * @param dataset
		 *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
		 *            JavaBean属性的数据类型有基本数据类型及String,Date
		 * @param out
		 *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
		 * @param pattern
		 *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
			// 声明一个工作薄
			XSSFWorkbook workbook = new XSSFWorkbook();
			// 生成一个表格
			XSSFSheet sheet = workbook.createSheet(title);
			// 设置表格默认列宽度为15个字节
			sheet.setDefaultColumnWidth(20);
			// 生成一个样式
			XSSFCellStyle style = workbook.createCellStyle();
			// 设置这些样式
			style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
			style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
			style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
			style.setBorderRight(XSSFCellStyle.BORDER_THIN);
			style.setBorderTop(XSSFCellStyle.BORDER_THIN);
			style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
			// 生成一个字体
			XSSFFont font = workbook.createFont();
			font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
			font.setFontName("宋体"); 
			font.setColor(new XSSFColor(java.awt.Color.BLACK));
			font.setFontHeightInPoints((short) 11);
			// 把字体应用到当前的样式
			style.setFont(font);
			// 生成并设置另一个样式
			XSSFCellStyle style2 = workbook.createCellStyle();
			style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
			style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
			style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
			style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
			style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
			style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
			style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
			style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
			// 生成另一个字体
			XSSFFont font2 = workbook.createFont();
			font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
			// 把字体应用到当前的样式
			style2.setFont(font2);
	 
			// 产生表格标题行
			XSSFRow row = sheet.createRow(0);
			XSSFCell cellHeader;
			for (int i = 0; i < headers.length; i++) {
				cellHeader = row.createCell(i);
				cellHeader.setCellStyle(style);
				cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
			}
	 
			// 遍历集合数据,产生数据行
			Iterator<T> it = dataset.iterator();
			int index = 0;
			T t;
			Field[] fields;
			Field field;
			XSSFRichTextString richString;
			Pattern p = Pattern.compile("^//d+(//.//d+)?$");
			Matcher matcher;
			String fieldName;
			String getMethodName;
			XSSFCell cell;
			Class tCls;
			Method getMethod;
			Object value;
			String textValue;
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			while (it.hasNext()) {
				index++;
				row = sheet.createRow(index);
				t = (T) it.next();
				// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
				fields = t.getClass().getDeclaredFields();
				for (int i = 0; i < fields.length; i++) {
					cell = row.createCell(i);
					cell.setCellStyle(style2);
					field = fields[i];
					fieldName = field.getName();
					getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
							+ fieldName.substring(1);
					try {
						tCls = t.getClass();
						getMethod = tCls.getMethod(getMethodName, new Class[] {});
						value = getMethod.invoke(t, new Object[] {});
						// 判断值的类型后进行强制类型转换
						textValue = null;
						if (value instanceof Integer) {
							cell.setCellValue((Integer) value);
						} else if (value instanceof Float) {
							textValue = String.valueOf((Float) value);
							cell.setCellValue(textValue);
						} else if (value instanceof Double) {
							textValue = String.valueOf((Double) value);
							cell.setCellValue(textValue);
						} else if (value instanceof Long) {
							cell.setCellValue((Long) value);
						}
						if (value instanceof Boolean) {
							textValue = "是";
							if (!(Boolean) value) {
								textValue = "否";
							}
						} else if (value instanceof Date) {
							textValue = sdf.format((Date) value);
						} else {
							// 其它数据类型都当作字符串简单处理
							if (value != null) {
								textValue = value.toString();
							}
						}
						if (textValue != null) {
							matcher = p.matcher(textValue);
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue));
							} else {
								richString = new XSSFRichTextString(textValue);
								cell.setCellValue(richString);
							}
						}
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					} finally {
						// 清理资源
					}
				}
			}
			try {
				workbook.write(out);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		
		/**
		 * <p>
		 * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
		 * 此方法生成2003版本的excel,文件名后缀:xls <br>
		 * </p>
		 * 
		 * @param title
		 *            表格标题名
		 * @param headers
		 *            表格头部标题集合
		 * @param dataset
		 *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
		 *            JavaBean属性的数据类型有基本数据类型及String,Date
		 * @param out
		 *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
		 * @param pattern
		 *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
			// 声明一个工作薄
			HSSFWorkbook workbook = new HSSFWorkbook();
			// 生成一个表格
			HSSFSheet sheet = workbook.createSheet(title);
			// 设置表格默认列宽度为15个字节
			sheet.setDefaultColumnWidth(20);
			// 生成一个样式
			HSSFCellStyle style = workbook.createCellStyle();
			// 设置这些样式
			style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style.setBorderTop(HSSFCellStyle.BORDER_THIN);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			// 生成一个字体
			HSSFFont font = workbook.createFont();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			font.setFontName("宋体"); 
			font.setColor(HSSFColor.WHITE.index);
			font.setFontHeightInPoints((short) 11);
			// 把字体应用到当前的样式
			style.setFont(font);
			// 生成并设置另一个样式
			HSSFCellStyle style2 = workbook.createCellStyle();
			style2.setFillForegroundColor(HSSFColor.WHITE.index);
			style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
			style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 生成另一个字体
			HSSFFont font2 = workbook.createFont();
			font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
			// 把字体应用到当前的样式
			style2.setFont(font2);
	 
			// 产生表格标题行
			HSSFRow row = sheet.createRow(0);
			HSSFCell cellHeader;
			for (int i = 0; i < headers.length; i++) {
				cellHeader = row.createCell(i);
				cellHeader.setCellStyle(style);
				cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
			}
	 
			// 遍历集合数据,产生数据行
			Iterator<T> it = dataset.iterator();
			int index = 0;
			T t;
			Field[] fields;
			Field field;
			HSSFRichTextString richString;
			Pattern p = Pattern.compile("^//d+(//.//d+)?$");
			Matcher matcher;
			String fieldName;
			String getMethodName;
			HSSFCell cell;
			Class tCls;
			Method getMethod;
			Object value;
			String textValue;
			SimpleDateFormat sdf = new SimpleDateFormat(pattern);
			while (it.hasNext()) {
				index++;
				row = sheet.createRow(index);
				t = (T) it.next();
				// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
				fields = t.getClass().getDeclaredFields();
				for (int i = 0; i < fields.length; i++) {
					cell = row.createCell(i);
					cell.setCellStyle(style2);
					field = fields[i];
					fieldName = field.getName();
					getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
							+ fieldName.substring(1);
					try {
						tCls = t.getClass();
						getMethod = tCls.getMethod(getMethodName, new Class[] {});
						value = getMethod.invoke(t, new Object[] {});
						// 判断值的类型后进行强制类型转换
						textValue = null;
						if (value instanceof Integer) {
							cell.setCellValue((Integer) value);
						} else if (value instanceof Float) {
							textValue = String.valueOf((Float) value);
							cell.setCellValue(textValue);
						} else if (value instanceof Double) {
							textValue = String.valueOf((Double) value);
							cell.setCellValue(textValue);
						} else if (value instanceof Long) {
							cell.setCellValue((Long) value);
						}
						if (value instanceof Boolean) {
							textValue = "是";
							if (!(Boolean) value) {
								textValue = "否";
							}
						} else if (value instanceof Date) {
							textValue = sdf.format((Date) value);
						} else {
							// 其它数据类型都当作字符串简单处理
							if (value != null) {
								textValue = value.toString();
							}
						}
						if (textValue != null) {
							matcher = p.matcher(textValue);
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue));
							} else {
								richString = new HSSFRichTextString(textValue);
								cell.setCellValue(richString);
							}
						}
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					} finally {
						// 清理资源
					}
				}
			}
			try {
				workbook.write(out);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

}

可以包装一下实现网页的导出;

package com.casic.util;

import java.net.URLEncoder;
import java.util.Collection;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class ExportWrapper<T> extends ExportUtils<T> {
	
	
	
	public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response,String version) {
		try {
			response.setContentType("application/vnd.ms-excel");  
    		response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xls");
			if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
				exportExcel2003(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd hh:mm:ss");
			}else{
				exportExcel2007(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd hh:mm:ss");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

3.PDFUtil(PDF加水印,图片转PDF,PDF转图片)

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <!--中文乱码-->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.13</version>
        </dependency>

        <!-- pdf转图片 -->
        <dependency>
            <groupId>org.icepdf.os</groupId>
            <artifactId>icepdf-core</artifactId>
            <version>6.1.2</version>
        </dependency>
        


    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>

package mirror.utils;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import mirror.file.FileList;
import org.icepdf.core.util.GraphicsRenderingHints;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;


/**
 * @Author: hekaikai
 * @Date: 2020/10/30 10:43
 */
public class PDFUtil {


    public static void main(String[] args) throws Exception {
        //PDF加水印
//        String pdfPath="D:\\workspace\\idea\\MirrorWeb\\target\\MirrorWeb-1.0-SNAPSHOT\\WEB-INF\\classes\\pdf\\a.pdf";
//        String resultPath="D:\\workspace\\idea\\MirrorWeb\\target\\MirrorWeb-1.0-SNAPSHOT\\WEB-INF\\classes\\pdf\\resultFile.pdf";
//        String imgPath="D:\\workspace\\idea\\MirrorWeb\\target\\MirrorWeb-1.0-SNAPSHOT\\WEB-INF\\classes\\kai.png";
//        waterMarkText(pdfPath,resultPath,"和凯凯:www.alivecaren.com");
//        waterMarkPicture(pdfPath,resultPath,imgPath);

        //图片转PDF
//        ArrayList<String> imageUrllist = new ArrayList<String>();
//        imageUrllist.add("D:\\test\\a.jpg");
//        imageUrllist.add("D:\\test\\b.jpg");
//        imageUrllist.add("D:\\test\\c.jpg");
//        imageUrllist.add("D:\\test\\d.jpg");
//        String pdfUrl = "D:\\test\\test.pdf";
//        Pdf(imageUrllist,pdfUrl);

        //PDF转图片
//        String pdfPath="D:\\workspace\\idea\\MirrorWeb\\target\\MirrorWeb-1.0-SNAPSHOT\\WEB-INF\\classes\\pdf\\a.pdf";
//        String path="D:\\test\\alive\\";
//        pdf2Pic(pdfPath,path,"aliveCaren");


    }

    /**
     * 给pdf文件加文字水印
     * @param inputFile 源文件路径
     * @param outputFile 输出文件路径
     * @param waterMarkName 水印内容
     * @return
     */
    public static boolean waterMarkText(String inputFile,String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //设置生成的PDF,需要密码才能编辑
            stamper.setEncryption(null, "123".getBytes(), PdfWriter.ALLOW_ASSEMBLY, false);
            //这里的字体设置比较关键,这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().
                        getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
                float x = 290;//pageRect.getWidth() / 2;
                float y = 400;//pageRect.getHeight() / 2;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);//在内容上方加水印
                //under = stamper.getUnderContent(i);// 在内容下方加水印
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度范围为0到1
                gs.setFillOpacity(0.3f);
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 35);//字体大小
                under.setColorFill(BaseColor.BLACK);//字体颜色
                // 水印文字成45度角倾斜
                under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 45);
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            reader.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 给pdf文件加图片水印
     * @param inputFile 源文件路径
     * @param outputFile 输出文件路径
     * @param imagePath 图片路径
     * @return
     */
    public static boolean waterMarkPicture(String inputFile,String outputFile, String imagePath) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //设置生成的PDF,需要密码才能编辑
            stamper.setEncryption(null, "123".getBytes(), PdfWriter.ALLOW_ASSEMBLY, false);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().
                        getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
                float x = 290;//pageRect.getWidth() / 2;
                float y = 400;//pageRect.getHeight() / 2;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);//在内容上方加水印
                //under = stamper.getUnderContent(i);// 在内容下方加水印
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度范围为0到1
                gs.setFillOpacity(0.3f);
                under.setGState(gs);
                under.beginText();

                Image image = Image.getInstance(imagePath);
                // 设置坐标 绝对位置 X Y
                image.setAbsolutePosition(200, 300);
                // 设置旋转弧度
                image.setRotation(30);// 旋转 弧度
                // 设置旋转角度
                image.setRotationDegrees(45);// 旋转 角度
                // 设置等比缩放
                image.scalePercent(90);// 依照比例缩放
                // image.scaleAbsolute(200,100);//自定义大小
                // 设置透明度
                under.setGState(gs);
                // 添加水印图片
                under.addImage(image);
                // 设置透明度
                under.setGState(gs);

                //结束设置
                under.endText();
                under.stroke();
            }
            stamper.close();
            reader.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 图片集合转PDF
     * @param imageUrllist
     * @param mOutputPdfFileName
     * @return
     */
    public static File Pdf(ArrayList<String> imageUrllist, String mOutputPdfFileName) {

        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
        try {
            PdfWriter
                    .getInstance(doc, new FileOutputStream(mOutputPdfFileName));
            doc.open();
            for (int i = 0; i < imageUrllist.size(); i++) {
                doc.newPage();
                BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
                Paragraph paragraph = new Paragraph();
                paragraph.setFont(new Font(base));
                paragraph.add("简单使用iText哈哈哈oasdf");
                doc.add(paragraph);

                Image png1 = Image.getInstance(imageUrllist.get(i));
                float heigth = png1.getHeight();
                float width = png1.getWidth();
                int percent = getPercent2(heigth, width);
                png1.setAlignment(Image.MIDDLE);
                png1.scalePercent(percent+3);// 表示是原来图像的比例;
                doc.add(png1);
            }
            doc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File mOutputPdfFile = new File(mOutputPdfFileName);
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile;
    }

    /**
     * 第一种解决方案 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
     */
    public static int getPercent(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        if (h > w) {
            p2 = 297 / h * 100;
        } else {
            p2 = 210 / w * 100;
        }
        p = Math.round(p2);
        return p;
    }

    /**
     * 第二种解决方案,统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
     */
    public static int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    /**
     * PDF 转图片
     * @param pdfPath
     * @param path 放图片的文件夹
     * @param fileName 每一个图片的名称
     * @throws Exception
     */
    public static void pdf2Pic(String pdfPath, String path, String fileName) throws Exception {
        org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度
        float rotation = 0f;
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = (BufferedImage)
                    document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
            RenderedImage rendImage = image;
            try {
                File fileDir = new File(path);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                String imgName = fileName + i + ".png";
                File file = new File(path + imgName);
                ImageIO.write(rendImage, "png", file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
    }
}

4.修改配置文件工具类

修改 yml,properties,ini 格式文件

import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.*;

/**
 * @Author: hekaikai
 * @Date: 2020/11/6 16:57
 */
public class UpdateYml {


    /**
     * 修改yml配置文件中的 reader.store.dir
     * @param file 配置文件
     * @param readerStoreDir 值
     */
    public static void update(File file,String readerStoreDir){
        Yaml yml =null;
        Map<String,Object> obj =null;
        try (FileInputStream in = new FileInputStream(file)){
            yml = new Yaml();
            obj = (Map)yml.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        HashMap<String,Object> reader = (HashMap<String, Object>) obj.get("reader");
        HashMap<String,Object> store = (HashMap<String, Object>) reader.get("store");
        Object dir = store.get("dir");
        String s = String.valueOf(dir);
        store.put("dir", readerStoreDir);

        try (FileWriter writer = new FileWriter(file)) {
            //writer.write(yml.dump(obj));
            writer.write(yml.dumpAsMap(obj));
            //writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.BLOCK));
            //可以自定义写入格式
            //writer.write(yml.dumpAs(obj, Tag.MAP, DumperOptions.FlowStyle.FLOW));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("修改yml文件出错了");
        }
    }

    /**
     * 修改项目的 properties文件
     * @param propertiesPath
     */
    public static void updatePropertiesJdbc(String propertiesPath){
        OutputStream fos=null;
        try {
            Properties props=new Properties();
            props.load(new FileInputStream(propertiesPath));
            props.setProperty("jdbc.url", "jdbc:mysql://127.0.0.1:3306/doc_standards?characterEncoding=UTF-8");
            props.setProperty("jdbc.username", "root");
            props.setProperty("jdbc.password", "123456");
            fos =new FileOutputStream(propertiesPath);
            props.store(fos, "修改jdbc");
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    /**
     * 更新配置文件 key=value 格式文件
     * @param configPath
     * @param map
     */
    public static void updateConfigFile(String configPath, Map<String, String> map) {
        Map<String, String> listMap = getListMap(new File(configPath));
        for (Map.Entry<String, String> entry : map.entrySet()) {
            listMap.put(entry.getKey(),entry.getValue());
        }

        File file=new File(configPath);
        try (
                OutputStream out=new FileOutputStream(file,false);
                OutputStreamWriter osw=new OutputStreamWriter(out,"utf-8");
                BufferedWriter bw=new BufferedWriter(osw);
                ){
            for (Map.Entry<String, String> entry : listMap.entrySet()) {
                bw.write(entry.getKey()+"="+entry.getValue());
                bw.newLine();
            }
            bw.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private static Map<String,String> getListMap(File file){
        Map<String,String> map=new LinkedHashMap<>();
        List<String> stringList=new ArrayList<>();

        try(InputStream in=new FileInputStream(file);
            InputStreamReader inr=new InputStreamReader(in,"utf-8");
            BufferedReader br=new BufferedReader(inr);
        ){
            String str;
            while ((str=br.readLine())!=null){
                stringList.add(str);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        for (String line : stringList) {
            if(line.startsWith("#")) {
                continue;
            }
            if(isWhiteSpace(line)) {
                continue;
            }
            if(!line.contains("=")){
                continue;
            }
            int fd = line.indexOf("=");
            String key = line.substring(0, fd);
            String value = line.substring(fd + 1);
            map.put(key,value);
        }
        return map;

    }

    private static boolean isWhiteSpace(String line) {
        return line.replace(" ", "").equals("");
    }


}

5.java 获取服务器参数

<dependency>
	<groupId>org.hyperic</groupId>
	<artifactId>sigar</artifactId>
	<version>1.6.5.132</version>
</dependency>

no sigar-amd64-winnt.dll in java.library.path

需要一个dll文件:
dll文件(windows 和 linux版)


import org.hyperic.sigar.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Properties;


public class SigarUtil {

	public static void main(String[] args) {
		try {
			// System信息,从jvm获取
			property();
			System.out.println("----------------------------------");
			// cpu信息
			cpu();
			System.out.println("----------------------------------");
			// 内存信息
			memory();
			System.out.println("----------------------------------");
			// 操作系统信息
			os();
			System.out.println("----------------------------------");
			// 用户信息
			who();
			System.out.println("----------------------------------");
			// 文件系统信息
			file();
			System.out.println("----------------------------------");
			// 网络信息
			net();
			System.out.println("----------------------------------");
			// 以太网信息
			ethernet();
			System.out.println("----------------------------------");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	private static void property() throws UnknownHostException {
		Runtime r = Runtime.getRuntime();
		Properties props = System.getProperties();
		InetAddress addr;
		addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress();
		Map<String, String> map = System.getenv();
		// 获取用户名
		String userName = map.get("USERNAME");
		// 获取计算机名
		String computerName = map.get("COMPUTERNAME");
		// 获取计算机域名
		String userDomain = map.get("USERDOMAIN");
		System.out.println("用户名:    " + userName);
		System.out.println("计算机名:    " + computerName);
		System.out.println("计算机域名:    " + userDomain);
		System.out.println("本地ip地址:    " + ip);
		System.out.println("本地主机名:    " + addr.getHostName());
		System.out.println("JVM可以使用的总内存:    " + r.totalMemory());
		System.out.println("JVM可以使用的剩余内存:    " + r.freeMemory());
		System.out.println("JVM可以使用的处理器个数:    " + r.availableProcessors());
		System.out.println("Java的运行环境版本:    " + props.getProperty("java.version"));
		System.out.println("Java的运行环境供应商:    " + props.getProperty("java.vendor"));
		System.out.println("Java供应商的URL:    " + props.getProperty("java.vendor.url"));
		System.out.println("Java的安装路径:    " + props.getProperty("java.home"));
		System.out.println("Java的虚拟机规范版本:    " + props.getProperty("java.vm.specification.version"));
		System.out.println("Java的虚拟机规范供应商:    " + props.getProperty("java.vm.specification.vendor"));
		System.out.println("Java的虚拟机规范名称:    " + props.getProperty("java.vm.specification.name"));
		System.out.println("Java的虚拟机实现版本:    " + props.getProperty("java.vm.version"));
		System.out.println("Java的虚拟机实现供应商:    " + props.getProperty("java.vm.vendor"));
		System.out.println("Java的虚拟机实现名称:    " + props.getProperty("java.vm.name"));
		System.out.println("Java运行时环境规范版本:    " + props.getProperty("java.specification.version"));
		System.out.println("Java运行时环境规范供应商:    " + props.getProperty("java.specification.vender"));
		System.out.println("Java运行时环境规范名称:    " + props.getProperty("java.specification.name"));
		System.out.println("Java的类格式版本号:    " + props.getProperty("java.class.version"));
		System.out.println("Java的类路径:    " + props.getProperty("java.class.path"));
		System.out.println("加载库时搜索的路径列表:    " + props.getProperty("java.library.path"));
		System.out.println("默认的临时文件路径:    " + props.getProperty("java.io.tmpdir"));
		System.out.println("一个或多个扩展目录的路径:    " + props.getProperty("java.ext.dirs"));
		System.out.println("操作系统的名称:    " + props.getProperty("os.name"));
		System.out.println("操作系统的构架:    " + props.getProperty("os.arch"));
		System.out.println("操作系统的版本:    " + props.getProperty("os.version"));
		System.out.println("文件分隔符:    " + props.getProperty("file.separator"));
		System.out.println("路径分隔符:    " + props.getProperty("path.separator"));
		System.out.println("行分隔符:    " + props.getProperty("line.separator"));
		System.out.println("用户的账户名称:    " + props.getProperty("user.name"));
		System.out.println("用户的主目录:    " + props.getProperty("user.home"));
		System.out.println("用户的当前工作目录:    " + props.getProperty("user.dir"));
	}

	private static void memory() throws SigarException {
		Sigar sigar = new Sigar();
		Mem mem = sigar.getMem();
		// 内存总量
		System.out.println("内存总量:    " + mem.getTotal() / 1024L + "K av");
		// 当前内存使用量
		System.out.println("当前内存使用量:    " + mem.getUsed() / 1024L + "K used");
		// 当前内存剩余量
		System.out.println("当前内存剩余量:    " + mem.getFree() / 1024L + "K free");
		Swap swap = sigar.getSwap();
		// 交换区总量
		System.out.println("交换区总量:    " + swap.getTotal() / 1024L + "K av");
		// 当前交换区使用量
		System.out.println("当前交换区使用量:    " + swap.getUsed() / 1024L + "K used");
		// 当前交换区剩余量
		System.out.println("当前交换区剩余量:    " + swap.getFree() / 1024L + "K free");
	}

	private static void cpu() throws SigarException {
		Sigar sigar = new Sigar();
		CpuInfo[] infos = sigar.getCpuInfoList();
		CpuPerc[] cpuList;

		System.out.println("cpu 总量参数情况:" + sigar.getCpu());
		System.out.println("cpu 总百分比情况:" + sigar.getCpuPerc());

		cpuList = sigar.getCpuPercList();
		// 不管是单块CPU还是多CPU都适用
		for (int i = 0; i < infos.length; i++) {
			CpuInfo info = infos[i];
			System.out.println("第" + (i + 1) + "块CPU信息");
			// CPU的总量MHz
			System.out.println("CPU的总量MHz:    " + info.getMhz());
			// 获得CPU的卖主,如:Intel
			System.out.println("CPU生产商:    " + info.getVendor());
			// 获得CPU的类别
			System.out.println("CPU类别:    " + info.getModel());
			// 缓冲存储器数量
			System.out.println("CPU缓存数量:    " + info.getCacheSize());
			printCpuPerc(cpuList[i]);
		}
	}

	private static void printCpuPerc(CpuPerc cpu) {
		System.out.println("CPU用户使用率:    " + CpuPerc.format(cpu.getUser()));
		System.out.println("CPU系统使用率:    " + CpuPerc.format(cpu.getSys()));
		System.out.println("CPU当前等待率:    " + CpuPerc.format(cpu.getWait()));
		System.out.println("CPU当前错误率:    " + CpuPerc.format(cpu.getNice()));
		System.out.println("CPU当前空闲率:    " + CpuPerc.format(cpu.getIdle()));
		System.out.println("CPU总的使用率:    " + CpuPerc.format(cpu.getCombined()));
	}

	private static void os() {
		OperatingSystem os = OperatingSystem.getInstance();
		// 操作系统内核类型如: 386、486、586等x86
		System.out.println("操作系统:    " + os.getArch());
		System.out.println("操作系统CpuEndian():    " + os.getCpuEndian());
		System.out.println("操作系统DataModel():    " + os.getDataModel());
		// 系统描述
		System.out.println("操作系统的描述:    " + os.getDescription());
		// 操作系统类型
		 System.out.println("OS.getName():    " + os.getName());
		 System.out.println("OS.getPatchLevel():    " + os.getPatchLevel());
		// 操作系统的卖主
		System.out.println("操作系统的卖主:    " + os.getVendor());
		// 卖主名称
		System.out.println("操作系统的卖主名:    " + os.getVendorCodeName());
		// 操作系统名称
		System.out.println("操作系统名称:    " + os.getVendorName());
		// 操作系统卖主类型
		System.out.println("操作系统卖主类型:    " + os.getVendorVersion());
		// 操作系统的版本号
		System.out.println("操作系统的版本号:    " + os.getVersion());
	}

	private static void who() throws SigarException {
		Sigar sigar = new Sigar();
		Who[] whos = sigar.getWhoList();
		if (whos != null && whos.length > 0) {
			for (Who who : whos) {
				System.out.println("用户控制台:    " + who.getDevice());
				System.out.println("用户host:    " + who.getHost());
				// 当前系统进程表中的用户名
				System.out.println("当前系统进程表中的用户名:    " + who.getUser());
			}
		}
	}

	private static void file() throws Exception {
		Sigar sigar = new Sigar();
		FileSystem[] fsList = sigar.getFileSystemList();
		for (int i = 0; i < fsList.length; i++) {
			System.out.println("分区的盘符名称" + i);
			FileSystem fs = fsList[i];
			// 分区的盘符名称
			System.out.println("盘符名称:    " + fs.getDevName());
			// 分区的盘符名称
			System.out.println("盘符路径:    " + fs.getDirName());
			System.out.println("盘符标志:    " + fs.getFlags());
			// 文件系统类型,比如 FAT32、NTFS
			System.out.println("盘符类型:    " + fs.getSysTypeName());
			// 文件系统类型名,比如本地硬盘、光驱、网络文件系统等
			System.out.println("盘符类型名:    " + fs.getTypeName());
			// 文件系统类型
			System.out.println("盘符文件系统类型:    " + fs.getType());
			FileSystemUsage usage=null;
			try {
				usage = sigar.getFileSystemUsage(fs.getDirName());
				switch (fs.getType()) {
					// TYPE_UNKNOWN :未知
					case 0: break;
					// TYPE_NONE
					case 1: break;
					// TYPE_LOCAL_DISK : 本地硬盘
					case 2:
						// 文件系统总大小
						System.out.println(fs.getDevName() + "总大小:    " + usage.getTotal() + "KB");
						// 文件系统剩余大小
						System.out.println(fs.getDevName() + "剩余大小:    " + usage.getFree() + "KB");
						// 文件系统可用大小
						System.out.println(fs.getDevName() + "可用大小:    " + usage.getAvail() + "KB");
						// 文件系统已经使用量
						System.out.println(fs.getDevName() + "已经使用量:    " + usage.getUsed() + "KB");
						double usePercent = usage.getUsePercent() * 100D;
						// 文件系统资源的利用率
						System.out.println(fs.getDevName() + "资源的利用率:    " + usePercent + "%");
						break;
					// TYPE_NETWORK :网络
					case 3: break;
					// TYPE_RAM_DISK :闪存
					case 4: break;
					// TYPE_CD_ROM :光驱
					case 5: break;
					// TYPE_SWAP :页面交换
					case 6: break;
					default: break;
				}
			System.out.println(fs.getDevName() + "读出:" + usage.getDiskReads());
			System.out.println(fs.getDevName() + "写入:" + usage.getDiskWrites());
			}catch (Exception e){
				e.printStackTrace();
			}
		}
	}

	private static void net() throws Exception {
		Sigar sigar = new Sigar();
		String[] ifNames = sigar.getNetInterfaceList();
		for (String name : ifNames) {
			NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
			System.out.println("网络设备名:    " + name);
			System.out.println("IP地址:    " + ifconfig.getAddress());
			System.out.println("子网掩码:    " + ifconfig.getNetmask());
			if ((ifconfig.getFlags() & 1L) <= 0L) {
				System.out.println("!IFF_UP...skipping getNetInterfaceStat");
				continue;
			}
			NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
			System.out.println(name + "接收的总包裹数:" + ifstat.getRxPackets());
			System.out.println(name + "发送的总包裹数:" + ifstat.getTxPackets());
			System.out.println(name + "接收到的总字节数:" + ifstat.getRxBytes());
			System.out.println(name + "发送的总字节数:" + ifstat.getTxBytes());
			System.out.println(name + "接收到的错误包数:" + ifstat.getRxErrors());
			System.out.println(name + "发送数据包时的错误数:" + ifstat.getTxErrors());
			System.out.println(name + "接收时丢弃的包数:" + ifstat.getRxDropped());
			System.out.println(name + "发送时丢弃的包数:" + ifstat.getTxDropped());
		}
	}

	private static void ethernet() throws SigarException {
		Sigar sigar;
		sigar = new Sigar();
		String[] ifAces = sigar.getNetInterfaceList();
		for (String ifAce : ifAces) {
			NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifAce);
			if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
					|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
				continue;
			}
			System.out.println(cfg.getName() + "IP地址:" + cfg.getAddress());
			System.out.println(cfg.getName() + "网关广播地址:" + cfg.getBroadcast());
			System.out.println(cfg.getName() + "网卡MAC地址:" + cfg.getHwaddr());
			System.out.println(cfg.getName() + "子网掩码:" + cfg.getNetmask());
			System.out.println(cfg.getName() + "网卡描述信息:" + cfg.getDescription());
			System.out.println(cfg.getName() + "网卡类型" + cfg.getType());
		}
	}
}

6.java 远程ssh 连接 linux ,执行 shell

<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>
package com.alivecaren;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.*;
import java.util.Arrays;
import java.util.List;

/**
 *  java 远程ssh 连接 linux ,执行 shell
 */
public class Test02  {

	// java实现本地上传脚本 并执行
    public static void main(String[] args) throws IOException {
        //获取连接
        Connection connection = getConnection("127.0.0.1", 22, "root", "123456");
        //上传脚本文件
        boolean b = uploadFile(connection, "/root", "b.sh");
        System.out.println(b);
        //运行shell命令
        // sed -i \"s/\\r//\ : 这个命令是为了保证从windows上传的脚本可执行
        runSSH(connection, "chmod +x b.sh","sed -i \"s/\\r//\" b.sh","./b.sh");
    }


    /**
     *  上传文件
     *  注意:这个方法的 connection 没有关闭,根据业务逻辑自己选择
     */
    public static boolean uploadFile(Connection connection,String remoteFilePath,String localFilePath) {
        boolean bool=false;
        try {
            SCPClient scpClient = connection.createSCPClient();
            //scpClient.get(remoteFilePath, localFilePath);
            scpClient.put(localFilePath,remoteFilePath);
            bool=true;
        }catch(IOException ioe) {
            ioe.printStackTrace();
            bool =false;
        }finally {

//            connection.close();
        }
        return bool;
    }


    /**
     *  运行 shell 命令
     * @param conn
     * @param shells
     * @throws IOException
     */
    public static void  runSSH( Connection conn,String... shells) throws IOException {
        List<String> strings = Arrays.asList(shells);

        for (String shell : strings) {
            Session session = conn.openSession();
            //这个应该是设置 控制台输出格式
            session.requestPTY("vt100", 80, 24, 640, 480, null);
            session.execCommand(shell);

            // 得到输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(session.getStdout()));
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            session.close();
            br.close();
        }
        conn.close();
    }

    /**
     *  获取远程连接
     */
    private static Connection getConnection(String host,int port, String username,String password) throws IOException {
        Connection conn = new Connection(host,port);
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(username,
                password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        return conn;
    }



    //执行本地的cmd命令.(DOS命令)
    public static int runLocal(String cmd) throws IOException {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec(cmd);
        InputStream stdout = new StreamGobbler(p.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
        }
        return p.exitValue();
    }

}

7.树形结构构建方法

public static List<PageResourceTreeResp> buildTree(List<PermissionPageResourceEntity> entityList){
        // 创建一个 Map 来存储每个节点的引用
        Map<Long, PageResourceTreeResp> nodeMap = new HashMap<>();

        // 将每个 PermissionPageResourceEntity 转换为 PageResourceTreeResp 并存入 Map
        for (PermissionPageResourceEntity entity : entityList) {
            PageResourceTreeResp node = new PageResourceTreeResp();
            node.setId(entity.getId());
            node.setParentId(entity.getParentId());
            node.setSort(entity.getSort());
            node.setResourceType(entity.getResourceType());
            node.setResourceCode(entity.getResourceCode());
            node.setResourceName(entity.getResourceName());
            node.setBizData(entity.getBizData());
            node.setRemark(entity.getRemark());
            nodeMap.put(entity.getId(), node);
        }

        // 构建树结构
        List<PageResourceTreeResp> rootNodes = new ArrayList<>();
        for (PageResourceTreeResp node : nodeMap.values()) {
            if (node.getParentId() == 0L) {
                // 如果 parentId 为 null,则为根节点
                rootNodes.add(node);
            } else {
                // 否则,找到父节点并添加到父节点的 children 列表中
                PageResourceTreeResp parentNode = nodeMap.get(node.getParentId());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(node);
                }
            }
        }
        // 对根节点及其所有子节点进行排序
        sortTree(rootNodes);
        return rootNodes;
    }

    private static void sortTree(List<PageResourceTreeResp> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        nodes.sort(Comparator.comparingInt(PageResourceTreeResp::getSort));
        for (PageResourceTreeResp node : nodes) {
            if (node.getChildren() != null) {
                sortTree(node.getChildren());
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值