Detailed methods for reading LINUX directories and files in Java and reading Windows shared folders

Detailed methods for reading LINUX directories and files in Java and reading Windows shared folders

Recently, due to company needs, Java needs to read the device shared folder on Windows, but the final code needs to be placed on Linux. Therefore, there is a problem that the code developed on Windows does not take effect. Finally, after mounting the Windows shared folder on Linux, the reading program is rewritten to realize the function. I searched for relevant information on the Internet, but it was not very comprehensive. Now I am sharing the relevant code, hoping to help everyone!

The dependencies are as follows:

<dependencies>
        <dependency>
            <groupId>org.samba.jcifs</groupId>
            <artifactId>jcifs</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.2</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.1</version>
        </dependency>
    </dependencies>

1. Read all files in the shared folder under Windows

    @Resource
    private MaterialsService materialsService;
    @Resource
    private PurchaseOrderService purchaseOrderService;

    private static String USER_DOMAIN = "";  //域账号,没有可以不填
    private static String USER_ACCOUNT = "Equator";  //账号
    private static String USER_PWS = "equator";  //密码
    private static String SOURCE_URL = "smb://192.168.20.160/SQLBinaryData0140/gong_xiang_bao_gao/";//来源路径
    private static String TARGET_URL = "\\\\192.168.20.160\\SQLBinaryData0140\\ExamineItemByTestingEquipmentBak\\";//处理后转移路径
	/**
     * @Title listFiles
     * @Description 遍历指定目录下的文件(共享文件夹)
     * @author Created by Chen Yang
     * @date 2021-07-19
     */
    public void listFiles(String shareDirectory) throws Exception {
    
    
        long startTime = System.currentTimeMillis();

        // 域服务器验证
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(USER_DOMAIN, USER_ACCOUNT, USER_PWS);
        SmbFile remoteFile = new SmbFile(shareDirectory, auth);
        //System.out.println("远程共享目录访问耗时:【{}】" + (System.currentTimeMillis() - startTime));
        if (remoteFile.exists()) {
    
    
            SmbFile[] files = remoteFile.listFiles();
            //System.out.println("文件存在");
            for (SmbFile f : files) {
    
    
                //System.out.println(f.getName());
                if(f.getName().indexOf(".txt") > -1 || f.getName().indexOf(".TXT") > -1 ){
    
    
                    File file = new File(f.getUncPath());
                    //System.out.println(f.getUncPath());
                    ArrayList<ExamineByTestingEquipment> testCardItemMapList  = txt2String(file);
                    if(CollUtil.isNotEmpty(testCardItemMapList)){
    
    
                        this.insertBatch(testCardItemMapList);
                        //System.out.println(testCardItemMapList);
                    }
                    File targetFile = new File(new String((TARGET_URL+f.getName().toString()).getBytes("utf-8"),"utf-8"));
                    boolean result = removeFile(file,targetFile);
                    if (!result) {
    
    
                        throw new CswRuntimeException("文件移动失败!");
                    }
                }
            }
        } else {
    
    
            throw new CswRuntimeException("目录下无文件!");
        }
    }

2. Read all files in the shared folder under Linux

@Resource
    private MaterialsService materialsService;
    @Resource
    private PurchaseOrderService purchaseOrderService;

    private static String USER_DOMAIN = "";  //域账号,没有可以不填
    private static String USER_ACCOUNT = "Equator";  //账号
    private static String USER_PWS = "equator";  //密码
    private static String SOURCE_URL = "/share/gong_xiang_bao_gao/";//来源路径
    private static String TARGET_URL = "/share/ExamineItemByTestingEquipmentBak/";//处理后转移路径

    /**
     * @Title queryLinuxFileNames
     * @Description 遍历指定目录下的文件(LNIUX下)
     * @author Created by Chen Yang
     * @date 2021-07-19
     */
    public void queryLinuxFileNames(String path) throws Exception {
    
    
        File linuxFile=new File(path);
        if(linuxFile.exists()){
    
    
            File[] tempList = linuxFile.listFiles();
            System.out.println("该目录下对象个数:"+tempList.length);
            for(File f: tempList){
    
    
                if(f.getName().indexOf(".txt") > -1 || f.getName().indexOf(".TXT") > -1 ){
    
    
                    File file = new File(f.toString());
                    //System.out.println(f.getUncPath());
                    ArrayList<ExamineByTestingEquipment> testCardItemMapList  = txt2String(file);
                    if(CollUtil.isNotEmpty(testCardItemMapList)){
    
    
                        this.insertBatch(testCardItemMapList);
                        //System.out.println(testCardItemMapList);
                    }
                    File targetFile = new File(TARGET_URL+f.getName().toString());
                    boolean result = removeFile2(file,targetFile);
                    if (!result) {
    
    
                        System.out.println("文件移动失败!");
                    }
                }
            }
        }else{
    
    
            System.out.println("目录下无文件!");
        }
    }

3. Implement file reading

	/**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @author Created by Chen Yang
     * @return 返回文件内容
     */
    public ArrayList<ExamineByTestingEquipment> txt2String(File file){
    
    
        ArrayList<ExamineByTestingEquipment> testCardItemMapList = new ArrayList<ExamineByTestingEquipment>();
        String testCardItemnum = null;
        String itemCode = null;
        String poOrder = null;
        boolean flag = false;
        try{
    
    
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            int i = 0;
            ExamineByTestingEquipment examineByTestingEquipment;
            Materials materials;
            PurchaseOrder purchaseOrder;
            while((s = br.readLine())!=null){
    
    //使用readLine方法,一次读一行
                if(flag && s.indexOf("#") == -1){
    
    
                    if((s.split("\\s+").length > 1 && s.indexOf("TruePosition2D") > -1)  ||
                            (s.split("\\s+").length > 1 && s.indexOf("Perpendicular") > -1)){
    
    
                        examineByTestingEquipment = new ExamineByTestingEquipment();
                        materials = new Materials();
                        purchaseOrder = new PurchaseOrder();

                        materials.setCode(itemCode);
                        purchaseOrder.setCode(poOrder);
                        if(materialsService.getMaterials(materials) == null || purchaseOrderService.getPurchaseOrder(purchaseOrder) == null ){
    
    
                            continue;
                        }
                        examineByTestingEquipment.setId(IdWorker.getId());
                        examineByTestingEquipment.setMaterials(materials);
                        examineByTestingEquipment.setMaterialsId(materialsService.getMaterials(materials).getId());
                        examineByTestingEquipment.setPurchaseOrder(purchaseOrder);
                        examineByTestingEquipment.setPurchaseOrderId(purchaseOrderService.getPurchaseOrder(purchaseOrder).getId());
                        examineByTestingEquipment.setExamineNum(Integer.parseInt(testCardItemnum));
                        examineByTestingEquipment.setExamineName(s.split("\\s+")[0]);
                        examineByTestingEquipment.setExamineValue(s.split("\\s+")[1]);
                        examineByTestingEquipment.setVersion(examineByTestingEquipment.getVersion());
                        examineByTestingEquipment.setCreateUser("admin");
                        examineByTestingEquipment.setCreateUserId(Long.parseLong("1196980511038091266"));
                        examineByTestingEquipment.setGmtCreate(new Date());
                        examineByTestingEquipment.setModifiedUser("admin");
                        examineByTestingEquipment.setGmtModified(new Date());
                        testCardItemMapList.add(examineByTestingEquipment);
                    }
                }else{
    
    
                    flag = false;
                }
                if (s.indexOf("#") > -1 && !flag){
    
    
                    flag = true;
                    testCardItemnum = s.substring(1);
                }
                if(i == 5){
    
    
                    itemCode = s.trim();
                }
                if(i == 6){
    
    
                    poOrder = s.trim();
                }
                i += 1;
            }
            br.close();
        }catch(Exception e){
    
    
            e.printStackTrace();
        }
        //System.out.println(testCardItemMapList);
        return testCardItemMapList;
    }

4. Place the read files in another directory.
Method 1:

	/**
     * 移动文件到另一个目录
     */
    public boolean removeFile(File sourceFile, File targetFile){
    
    
        boolean result = sourceFile.renameTo(targetFile);
        return  result;
    }

Method 2:

	/**
     * 移动文件到另一个目录
     */
    public boolean removeFile2(File sourceFile, File targetFile){
    
    
        boolean result = false;
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
    
    
            //复制原文件
            BufferedReader br = new BufferedReader(new FileReader(sourceFile));//构造一个BufferedReader类来读取文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(targetFile));
            String s = null;
            while((s = br.readLine())!=null){
    
    
                bw.write(s);
                bw.newLine();
            }
            // 关闭流
            bw.close();
            br.close();
            //删除原文件
            if (sourceFile.exists() && targetFile.exists()) {
    
    
                result  = sourceFile.delete();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        //System.out.println(result);
        return  result;
    }

Guess you like

Origin blog.csdn.net/qq_38696286/article/details/119146951