Java - 校验文件内容是否修改

思路:使用MD5对文件内容进行加密, 得到字符串进行比较;-- 不可使用文件大小判断;

借鉴:参考Nacos源码,Nacos底层对配置文件的校验使用的是此方法

MD5Utils工具类:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Utils {

    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};
    
    private static final ThreadLocal<MessageDigest> MESSAGE_DIGEST_LOCAL = new ThreadLocal<MessageDigest>() {
        @Override
        protected MessageDigest initialValue() {
            try {
                return MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                return null;
            }
        }
    };
    
    /**
     * Calculate MD5 hex string.
     *
     * @param bytes byte arrays
     * @return MD5 hex string of input
     * @throws NoSuchAlgorithmException if can't load md5 digest spi.
     */
    public static String md5Hex(byte[] bytes) throws NoSuchAlgorithmException {
        try {
            MessageDigest messageDigest = MESSAGE_DIGEST_LOCAL.get();
            if (messageDigest != null) {
                return encodeHexString(messageDigest.digest(bytes));
            }
            throw new NoSuchAlgorithmException("MessageDigest get MD5 instance error");
        } finally {
            MESSAGE_DIGEST_LOCAL.remove();
        }
    }
    
    /**
     * Calculate MD5 hex string with encode charset.
     *
     * @param value  value
     * @param encode encode charset of input
     * @return MD5 hex string of input
     */
    public static String md5Hex(String value, String encode) {
        try {
            return md5Hex(value.getBytes(encode));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * Convert a byte array into a visible string.
     */
    public static String encodeHexString(byte[] bytes) {
        int l = bytes.length;
        
        char[] out = new char[l << 1];
        
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & bytes[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & bytes[i]];
        }
        
        return new String(out);
    }
}

FileTest测试工具类:

public class FileTest {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        File file1 = new File("C:\\Users\\Desktop\\文件1.txt");
        File file2 = new File("C:\\Users\\Desktop\\文件2.txt");
        File file3 = new File("C:\\Users\\Desktop\\文件3.txt");
        System.out.println(file1.length());
        System.out.println(file2.length());
        System.out.println(file3.length());

        String file1Md5 = MD5Utils.md5Hex(fileToBytes(file1)); //c4ca4238a0b923820dcc509a6f75849b
        System.out.println(file1Md5);
        String file2Md5 = MD5Utils.md5Hex(fileToBytes(file2)); //c4ca4238a0b923820dcc509a6f75849b
        System.out.println(file2Md5);
        String file3Md5 = MD5Utils.md5Hex(fileToBytes(file3)); //cfcd208495d565ef66e7dff9f98764da
        System.out.println(file3Md5);
    }

    /**
     * 文件转字节
     * @param file
     * @return
     */
    public static byte[] fileToBytes(File file) {
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        byte[] buffer = null;
        try{
            in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            int n;
            byte[] b = new byte[1024];
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n);
            }
            buffer = out.toByteArray();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            try {
                if (in != null){
                    in.close();
                }
                if (out != null){
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return buffer;
    }
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 用 Java 导入 Excel 文件并校验数据,将错误的数据标红并下载,需要使用一些第三方库,比如 Apache POI。下面是一个简单的代码示例: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelValidator { public static void main(String[] args) { try { // 读取 Excel 文件 FileInputStream fis = new FileInputStream("sample.xlsx"); XSSFWorkbook workbook = new XSSFWorkbook(fis); XSSFSheet sheet = workbook.getSheetAt(0); // 创建样式,用于标记错误数据 XSSFCellStyle style = workbook.createCellStyle(); XSSFFont font = workbook.createFont(); font.setColor(XSSFFont.COLOR_RED); style.setFont(font); // 遍历所有行,校验数据 for (int i = 0; i <= sheet.getLastRowNum(); i++) { XSSFRow row = sheet.getRow(i); for (int j = 0; j < row.getLastCellNum(); j++) { XSSFCell cell = row.getCell(j); if (cell.getStringCellValue().equals("error")) { cell.setCellStyle(style); } } } // 将修改后的 Excel 文件写入磁盘 FileOutputStream fos = new FileOutputStream("sample_output.xlsx"); workbook.write(fos); // 关闭文件流 fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个代码中,我们使用了 Apache POI 库来读取和写入 Excel 文件。首先, ### 回答2: 在Java中导入Excel文件并进行校验,并将错误的数据标红并下载的操作可以通过以下步骤实现。 首先,需要使用Java文件操作库(如Apache POI)来读取Excel文件。可以通过以下代码片段实现: ``` // 导入所需的库 import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.ss.usermodel.Row; // 读取Excel文件 Workbook workbook = new XSSFWorkbook(new FileInputStream("输入文件路径")); Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 // 循环遍历每一行数据 for (Row row : sheet) { // 根据所需数据位置读取数据,并进行校验 Cell cellA = row.getCell(0); // 假设数据在第一列 String inputData = cellA.getStringCellValue(); // 进行数据校验 boolean isValid = validate(inputData); // 如果数据校验不通过,将错误的单元格标红 if (!isValid) { CellStyle redCellStyle = workbook.createCellStyle(); redCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); redCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); cellA.setCellStyle(redCellStyle); } } // 保存并关闭Excel文件 FileOutputStream outputStream = new FileOutputStream("输出文件路径"); workbook.write(outputStream); workbook.close(); outputStream.close(); ``` 在上面的代码中,`validate`方法用于对每个单元格的数据进行校验,并根据校验结果设置相应的单元格样式。如果校验不通过,使用红色标记错误的单元格。最后,通过创建一个新的Excel文件并将标记后的数据写入其中,实现将错误的数据标红并下载的功能。 需要注意的是,以上代码只适用于处理XLSX格式的Excel文件。如果是处理XLS格式的文件,需要使用`HSSFWorkbook`类替换`XSSFWorkbook`类。 希望以上的回答能对您有所帮助! ### 回答3: 导入并校验Excel文件中的数据,并将错误的数据标红并下载,可以使用Java操作Excel文件和Apache POI库来实现。 1. 首先,需要引入Apache POI库的依赖。可以在项目的pom.xml文件中添加以下代码: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 读取Excel文件并进行数据校验。可以使用以下代码示例: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelValidation { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("input.xlsx")); Workbook workbook = new XSSFWorkbook(file); Sheet sheet = workbook.getSheetAt(0); // 遍历所有行(从第二行开始,第一行可能是表头) for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); Cell cell = row.getCell(0); // 获取第一列的数据 // 进行数据校验,若错误则将该单元格设置为红色 // 示例:判断数据是否为数字,若不是则标记为错误 try { double value = cell.getNumericCellValue(); } catch (NumberFormatException e) { CellStyle errorStyle = workbook.createCellStyle(); errorStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); cell.setCellStyle(errorStyle); } } file.close(); // 将修改后的Excel文件保存到新的目标文件 FileOutputStream outFile = new FileOutputStream(new File("output.xlsx")); workbook.write(outFile); outFile.close(); System.out.println("Excel文件校验完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 3. 上述代码会将校验错误的数据所在的单元格标记为红色,并将修改后的Excel文件保存为"output.xlsx"。 以上就是使用Java实现导入Excel文件校验、标红并下载的代码。您可以根据实际需求进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值