簡體   English   中英

如何連接從路徑到目錄的字符串以及目錄中的多個zip文件名?

[英]How to concatenate a string from path to directory and a multiple zip files names in a directory?

我正在研究一些腳本,以霧化幾乎每天都需要執行的手動功能。

我的第一個問題是從Path和zip文件名構建一個String。 第二個問題是循環瀏覽zip文件名(路徑+ zip文件名)。

這是具有多個zip文件的目錄的路徑: /Users/John.Smith/Desktop/Test_script/

這是許多壓縮文件之一的名稱: CRM_CI_20161016_000001_50661561.zip

最后,我需要遍歷每個zip文件名稱為50661561的目錄和子字符串,以便進行操作。

有人可以給我一個建議嗎?

這是我下面給出的僅處理一個zip文件的代碼:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;



public class UnzipUtilityTest {
    public static void main(String[] args) {



  // unzip file 

        String zipFilePath = "/Users/John.Smith/Desktop/Test_script/CRM_CI_20161016_000001_50661561.zip";
        String destDirectory = "/Users/John.Smith/Desktop/Test_script/test";
        UnzipUtility unzipper = new UnzipUtility();


        try {
            unzipper.unzip(zipFilePath, destDirectory);
        } catch (Exception ex) {

            System.out.println("ERROR:Unzip did not work");
        }


 // read provider id       
        String old_prov_id = zipFilePath.substring(66, 74);
        System.out.println("Old provider ID :"+old_prov_id );

 // add +1 to provider ID
        int new_provider_ID = Integer.parseInt(old_prov_id);
        new_provider_ID++;
        System.out.println("New provider ID :"+new_provider_ID );


 // convert provider-id INT into String   

      String str_provider_id = Integer.toString(new_provider_ID);  
      System.out.println("New String provider ID :"+str_provider_id );  

 // concatenate two String into one
        StringBuilder bufferPDF = new StringBuilder()
                .append(new_provider_ID).append(".pdf");
            System.out.println(bufferPDF.toString()); 

            StringBuilder bufferXML = new StringBuilder()
                    .append(new_provider_ID).append(".xml");
                System.out.println(bufferXML.toString()); 

  // convert names of XML and PDF      

       Path sourcePDF = Paths.get("/Users/John.Smith/Desktop/Test_script/test/50661561.pdf");
        try {
            Files.move(sourcePDF, sourcePDF.resolveSibling(bufferPDF.toString()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Path sourceXML = Paths.get("/Users/John.Smith/Desktop/Test_script/test/50661561.xml");
        try {
            Files.move(sourceXML, sourceXML.resolveSibling(bufferXML.toString()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    // change provider-id and filename in xml file    

           try {

                String filepath = "/Users/John.Smith/Desktop/Test_script/test/50661562.xml";

                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(filepath);

                // Get the root element provider-id 
                Node provider = doc.getElementsByTagName("provider-id").item(0);
                provider.setTextContent(str_provider_id);

                // Get the root element filename
                Node filename = doc.getElementsByTagName("filename").item(0);
                filename.setTextContent(str_provider_id);


                // write the content into xml file
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(new File(filepath));
                transformer.transform(source, result);

                System.out.println("Done");

               } catch (ParserConfigurationException pce) {
                pce.printStackTrace();
               } catch (TransformerException tfe) {
                tfe.printStackTrace();
               } catch (IOException ioe) {
                ioe.printStackTrace();
               } catch (SAXException sae) {
                sae.printStackTrace();
               }            

          }               
    }

如果您輸入正確,則主要問題是您的字符串類似

CRM_CI_20161016_000001_50661561.zip

而您想獲取50661561

如果是這樣,您可以簡單地使用String.lastIndexOf()方法。 只需做一個

String input = "CRM....
int indexOfLastUnderScore = input.lastIndexOf('_');
int indexOfZipExtension = input.lastIndexOf('.');
String substringWithNumer = input.substring(indexOfLastUnderScore+1, indexOfZipExtension);

當然,您也可以在這里使用正則表達式,但是從長遠來看,我認為將上述代碼之類的內容推入一個小的輔助方法中更容易維護。

(提示:我沒有通過編譯器運行我的代碼;因此請注意錯別字或細微的“一處走”錯誤;但是它應該足以使您繼續前進)

我會對此有所不同:

  1. 列出目錄中的所有文件
  2. 循環瀏覽文件列表中的項目
  3. 提取舊ID並增加它
  4. 處理新編號

例:

//you could probably make this nicer

String fileNamePattern = "CRM_CI_\\d{8}_\\d{6}_\\d{8}\\.zip";
String oldProvIdPattern = "CRM_CI_\\d{8}_\\d{6}_(\\d{8})\\.zip";

String pathToZips = "/Users/John.Smith/Desktop/Test_script/"
String destinationPath = "/Users/John.Smith/Desktop/Test_script/test";

File dir = new File(".");
FileFilter fileFilter = new RegexFileFilter(fileNamePattern);
File[] files = pathToZips.listFiles(fileFilter);
for (File file : files) {
    //Handle each zip here
    String zipPath = file.getAbsolutePath();  


    try {
        unzipper.unzip(zipPath, destinationPath);
    } catch (Exception ex) {
        System.out.println("ERROR:Unzip did not work");
    }

    Pattern pattern = Pattern.compile(oldProvIdPattern);
    Matcher matcher = pattern.matcher(file.getName());
    if (matcher.find()){
        String old_prov_id = matcher.group(1);
        System.out.println("Old provider ID :"+old_prov_id );

        // add +1 to provider ID
        int new_provider_ID = Integer.parseInt(old_prov_id);
        new_provider_ID++;
        System.out.println("New provider ID :"+new_provider_ID );

        // convert provider-id INT into String   

        String str_provider_id = Integer.toString(new_provider_ID);  
        System.out.println("New String provider ID :"+str_provider_id );  

        // concatenate two String into one
        StringBuilder bufferPDF = new StringBuilder()
                .append(new_provider_ID).append(".pdf");
            System.out.println(bufferPDF.toString()); 

            StringBuilder bufferXML = new StringBuilder()
                    .append(new_provider_ID).append(".xml");
                System.out.println(bufferXML.toString()); 

        // convert names of XML and PDF      

       Path sourcePDF = Paths.get("/Users/John.Smith/Desktop/Test_script/test/" + old_prov_id + ".pdf");
        try {
            Files.move(sourcePDF, sourcePDF.resolveSibling(bufferPDF.toString()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Path sourceXML = Paths.get("/Users/John.Smith/Desktop/Test_script/test/" + old_prov_id + ".xml");
        try {
            Files.move(sourceXML, sourceXML.resolveSibling(bufferXML.toString()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // change provider-id and filename in xml file    

        try {

        String filepath = "/Users/John.Smith/Desktop/Test_script/test/" + old_prov_id + ".xml";

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // Get the root element provider-id 
        Node provider = doc.getElementsByTagName("provider-id").item(0);
        provider.setTextContent(str_provider_id);

        // Get the root element filename
        Node filename = doc.getElementsByTagName("filename").item(0);
        filename.setTextContent(str_provider_id);


        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");

       } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
       } catch (TransformerException tfe) {
        tfe.printStackTrace();
       } catch (IOException ioe) {
        ioe.printStackTrace();
       } catch (SAXException sae) {
        sae.printStackTrace();
       }            

      }  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM