yangys
2025-08-12 8ede6183253248e497d391a0902bb5d41181b3bf
文件处理
已修改7个文件
240 ■■■■■ 文件已修改
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/controller/MachineFileController.java 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/entity/MachineFile.java 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/service/MachineFileService.java 94 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/service/ProgramNodeService.java 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/vo/ProgramNodeVO.java 4 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/task/MachineFileScanTask.java 88 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/test/MyTestController.java 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/controller/MachineFileController.java
@@ -19,6 +19,7 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List;
/**
@@ -49,12 +50,19 @@
    @GetMapping("/file-content")
    @Operation(summary = "获取机床目录文件内容", description = "工控网目录文件列表")
    public R<String> machineFileContent(Long id) {
        return R.data("临时内容");
        String content = machineFileService.getMachineFileContent(id);
        return R.data(content);
    }
    @PostMapping("/file-save")
    @Operation(summary = "保存机床文件", description = "保存机床文件到磁盘")
    public R<Void> machineFileSave(Long id,String content) {
        try {
            machineFileService.saveFileConent(id,content);
        } catch (IOException e) {
            log.error(e.getMessage());
            return R.fail(e.getMessage());
        }
        return R.success();
    }
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/entity/MachineFile.java
@@ -3,6 +3,8 @@
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.mp.base.BizEntity;
import java.util.Date;
@@ -54,4 +56,23 @@
    private Date fileCreateTime;
    private Date fileModifyDate;
    /**
     * 文件md5
     */
    private String md5;
    /**
     * 文件字节数
     */
    private Long fileSize;
    /**
     * 生成文件大小的显示文本
     * @return 显示文本
     */
    public String getFileSizeDisplay(){
        String disp = FileUtils.byteCountToDisplaySize(fileSize);
        //disp = StringUtils.replace(disp,"bytes","字节");
        return disp;
    }
}
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/service/MachineFileService.java
@@ -3,12 +3,28 @@
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BizServiceImpl;
import org.springblade.core.tool.utils.Charsets;
import org.springblade.core.tool.utils.Func;
import org.springblade.mdm.basesetting.machine.MachineService;
import org.springblade.mdm.basesetting.machine.entity.Machine;
import org.springblade.mdm.gkw.programnode.entity.MachineFile;
import org.springblade.mdm.gkw.programnode.mapper.MachineFileMapper;
import org.springblade.mdm.utils.FileContentUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
@@ -20,6 +36,84 @@
@Service
@AllArgsConstructor
public class MachineFileService extends BizServiceImpl<MachineFileMapper, MachineFile> {
    private final MachineService machineService;
    /**
     * 检测文件是否存在
     * @param name 文件名
     * @param md5 文件md5
     * @param machineCode 所属机床
     * @return 是否存在于库内
     */
    public boolean fileExists(String name, String md5,String machineCode) {
        return this.lambdaQuery().eq(MachineFile::getName, name).eq(MachineFile::getMd5, md5).eq(MachineFile::getMachineCode, machineCode).count()>0;
    }
    @Transactional(readOnly = true)
    public String getMachineFileContent(Long id) {
        MachineFile machineFile = getById(id);
        Machine machine = machineService.getByCode(machineFile.getMachineCode());
        String filePathStr = getBasePath(machine,machineFile.getDirType())+ File.separator+machineFile.getName();
        String content;
        Path filePath = Paths.get(filePathStr);
        if(!filePath.toFile().exists()){
            return StringUtils.EMPTY;
        }
        try (InputStream inputStream = Files.newInputStream(filePath)) {
            // 使用输入流读取文件内容
            content = FileContentUtil.getContentFromStream(inputStream);
        } catch (IOException e) {
            log.error("读取文件md5失败",e);
            return StringUtils.EMPTY;
        }
        return content;
    }
    /**
     * 获取基本路径
     * @param machine
     * @param dirType
     * @return
     */
    public static String getBasePath(Machine machine,String dirType){
        String dirPath;
        switch (dirType) {
            case MachineFile.DIR_TYPE_REC:
                dirPath = machine.getProgReceiveDir();
                break;
            case MachineFile.DIR_TYPE_SEND:
                dirPath = machine.getProgSendDir();
                break;
            case MachineFile.DIR_TYPE_TEMP:
                dirPath = machine.getProgTempDir();
                break;
            default:
                log.warn("目录类型不匹配:{}",dirType);
                return null;//不符合任何类型,直接退出
        }
        return dirPath;
    }
    @Transactional
    public void saveFileConent(Long id, String content) throws IOException {
        MachineFile machineFile = getById(id);
        Machine machine = machineService.getByCode(machineFile.getMachineCode());
        String filePathStr = getBasePath(machine,machineFile.getDirType())+ File.separator+machineFile.getName();
        Path filePath = Paths.get(filePathStr);
        String charsetName = "UTF-8";
        try (InputStream inputStream = Files.newInputStream(filePath)) {
            // 使用输入流读取文件内容
            charsetName = FileContentUtil.detectFromInputStream(inputStream);
        } catch (IOException e) {
            log.error("读取文件编码失败",e);
            throw new ServiceException("获取文件编码失败");
        }
        FileUtils.writeStringToFile(filePath.toFile(),content,charsetName);
    }
}
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/service/ProgramNodeService.java
@@ -10,6 +10,7 @@
import org.springblade.mdm.basesetting.machine.entity.Machine;
import org.springblade.mdm.commons.contants.ParamConstants;
import org.springblade.mdm.commons.service.ParamService;
import org.springblade.mdm.gkw.programnode.entity.MachineFile;
import org.springblade.mdm.gkw.programnode.entity.ProgramNode;
import org.springblade.mdm.gkw.programnode.entity.TreeDept;
import org.springblade.mdm.gkw.programnode.mapper.ProgramNodeMapper;
@@ -63,7 +64,7 @@
        for(TreeDept workshop : workshops) {
            ProgramNodeVO node = new ProgramNodeVO();
            node.setId(workshop.getId());
            node.setId(String.valueOf(workshop.getId()));
            node.setName(workshop.getDeptName());
            roots.add(node);
@@ -73,7 +74,7 @@
                .orderByAsc(TreeDept::getSort).list();
            for(TreeDept gd : gongduanList){
                ProgramNodeVO nodeGd = new ProgramNodeVO();
                nodeGd.setId(nodeGd.getId());
                nodeGd.setId(String.valueOf(gd.getId()));
                nodeGd.setName(gd.getDeptName());
                nodeGd.setParentId(gd.getParentId());
@@ -83,7 +84,7 @@
                machineService.lambdaQuery().eq(Machine::getOwnerDept,gd.getId()).list().forEach(machine -> {
                    ProgramNodeVO nodeMachine = new ProgramNodeVO();
                    nodeMachine.setName(machine.getCode());
                    nodeMachine.setId(machine.getId());
                    nodeMachine.setId(String.valueOf(machine.getId()));
                    nodeMachine.setMachineCode(machine.getCode());
                    addFolderNodes(nodeMachine);
@@ -102,19 +103,23 @@
    void addFolderNodes(ProgramNodeVO nodeMachine){
        ProgramNodeVO sendNode = new ProgramNodeVO();
        sendNode.setId(nodeMachine.getId()+"_"+MachineFile.DIR_TYPE_SEND);
        sendNode.setName("SEND");
        sendNode.setMachineCode(nodeMachine.getMachineCode());
        sendNode.setDirType("SEND");
        sendNode.setDirType(MachineFile.DIR_TYPE_SEND);
        //sendNode.setParentId(nodeMachine.getId());
        ProgramNodeVO recNode = new ProgramNodeVO();
        recNode.setId(nodeMachine.getId()+"_"+MachineFile.DIR_TYPE_REC);
        recNode.setName("REC");
        recNode.setMachineCode(nodeMachine.getMachineCode());
        recNode.setDirType("REC");
        recNode.setDirType(MachineFile.DIR_TYPE_REC);
        ProgramNodeVO tempNode = new ProgramNodeVO();
        tempNode.setId(nodeMachine.getId()+"_"+MachineFile.DIR_TYPE_TEMP);
        tempNode.setName("TEMP");
        tempNode.setMachineCode(nodeMachine.getMachineCode());
        tempNode.setDirType("TEMP");
        tempNode.setDirType(MachineFile.DIR_TYPE_TEMP);
        nodeMachine.setChildren(Arrays.asList(sendNode,recNode,tempNode));
    }
blade-service/blade-mdm/src/main/java/org/springblade/mdm/gkw/programnode/vo/ProgramNodeVO.java
@@ -12,7 +12,9 @@
@Setter
@Getter
@EqualsAndHashCode
public class ProgramNodeVO extends BaseVO {
public class ProgramNodeVO {
    @Schema(description = "节点id")
    private String id;
    @Schema(description = "节点名称")
    private String name;
    @Schema(description = "父ID,根节点父id=0")
blade-service/blade-mdm/src/main/java/org/springblade/mdm/task/MachineFileScanTask.java
@@ -1,5 +1,8 @@
package org.springblade.mdm.task;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.FileUtil;
import org.springblade.mdm.basesetting.machine.MachineService;
import org.springblade.mdm.basesetting.machine.entity.Machine;
@@ -12,6 +15,7 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -20,6 +24,7 @@
import java.util.Date;
import java.util.List;
@Slf4j
@Component
@EnableScheduling
public class MachineFileScanTask {
@@ -28,32 +33,77 @@
    @Autowired
    private MachineService machineService;
    // 每5秒执行一次
    @Scheduled(fixedRate = 1000000)
    //@Scheduled(fixedRate = 1000000)
    //@Scheduled(cron = "0 1 0 * * ?") // 每天上午0点1分执行
    @Scheduled(cron = "0 15 19 * * ?") //test
    public void executeEvery5Seconds() {
        System.out.println("定时任务执行: " + System.currentTimeMillis());
        scanMachineFile();
    }
    public void scanMachineFile() {
        List<Machine> machines = machineService.lambdaQuery().eq(Machine::getStatus,Machine.STATUS_ENABLE).list();
        for (Machine machine : machines) {
            scanReceiveDir(machine);
            try {
                scanDir(machine,MachineFile.DIR_TYPE_REC);
            }catch(Exception e) {
                log.error("REC扫描文件异常,机床"+machine.getCode(),e);
            }
            try {
                scanDir(machine,MachineFile.DIR_TYPE_SEND);
            }catch(Exception e) {
                log.error("SEND扫描文件异常,机床"+machine.getCode(),e);
            }
            try {
                scanDir(machine,MachineFile.DIR_TYPE_TEMP);
            }catch(Exception e) {
                log.error("TEMP扫描文件异常,机床"+machine.getCode(),e);
            }
        }
    }
    public void scanReceiveDir(Machine machine){
        List<File> files = FileUtil.list(machine.getProgReceiveDir());
        for(File f : files){
    /**
     * 扫描目录
     * @param machine 机床信息
     * @param dirType 目录类型
     * @throws IOException
     */
    public void scanDir(Machine machine,String dirType) throws IOException {
        //MachineFile.DIR_TYPE_REC
        String basePath = MachineFileService.getBasePath(machine,dirType);
        if(basePath == null) {
            log.warn("目录类型不匹配:{}",dirType);
            return;
        }
        Path dirPath = Paths.get(basePath);
        if(!dirPath.toFile().exists()){
            log.warn("扫描目录:{} 不存在",dirPath);
            return;
        }
        // 只包含普通文件
        List<Path> files = Files.list(dirPath)
            .filter(Files::isRegularFile).toList();
        byte[] buffer = new byte[2048];
        boolean exists;//文件是否存在于数据库中
        for (Path filePath : files) {
            exists = false;
            MachineFile mf = new MachineFile();
            mf.setName(f.getName());
            mf.setDirType(MachineFile.DIR_TYPE_REC);
            mf.setTenantId("000000");
            mf.setName(filePath.toFile().getName());
            mf.setDirType(dirType);
            mf.setMachineCode(machine.getCode());
            try {
                Path filePath = Paths.get(f.getPath());
                BasicFileAttributes attrs = Files.readAttributes(
                    filePath,
                    BasicFileAttributes.class
@@ -63,15 +113,31 @@
                Date creationDate = new Date(creationTime.toMillis());
                mf.setFileCreateTime(creationDate);
                FileTime modifyTime =attrs.lastModifiedTime();
                FileTime modifyTime = attrs.lastModifiedTime();
                mf.setFileModifyDate(new Date(modifyTime.toMillis()));
                mf.setFileSize(Files.size(filePath));
                try (InputStream inputStream = Files.newInputStream(filePath)) {
                    // 使用输入流读取文件内容
                    int bytesRead = inputStream.read(buffer);
                    mf.setMd5(DigestUtils.md5Hex(buffer));
                } catch (IOException e) {
                    log.error("读取文件md5失败",e);
                    continue;//有错误,掠过
                }
                exists = machineFileService.fileExists(mf.getName(),mf.getMd5(),machine.getCode());
                System.out.println("文件创建时间: " + creationDate);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("读取文件信息失败",e);
            }
            if(!exists) {
                machineFileService.save(mf);
            }else{
                log.info("文件已如果掠过:{}",filePath.getFileName());
            }
            machineFileService.save(mf);
        }
    }
}
blade-service/blade-mdm/src/main/java/org/springblade/mdm/test/MyTestController.java
@@ -5,6 +5,7 @@
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.mdm.basesetting.machine.entity.Machine;
import org.springblade.mdm.gkw.programnode.entity.MachineFile;
import org.springblade.mdm.program.entity.NcNode;
import org.springblade.mdm.program.service.NcNodeService;
import org.springblade.mdm.task.MachineFileScanTask;
@@ -64,8 +65,9 @@
    @Operation(summary = "test扫描", description = "test扫描")
    public R<Void> scan() throws IOException {
        Machine machine = new Machine();
        machine.setProgReceiveDir("d:/mdm");
        machineFileScanTask.scanReceiveDir(machine);
        machine.setCode("M_01_FN");
        machine.setProgReceiveDir("d:/data/machine1/rec");
        machineFileScanTask.scanDir(machine, MachineFile.DIR_TYPE_REC);
        return R.success();
    }