Processing based on Java + HttpClient + TestNG interface test automation framework (eight) for the file ------

  In the actual interface testing is sometimes necessary to upload and download files as appropriate. In the relatively small number of files, we can certainly deal directly (such as several interfaces with a file). But if we need to use the uploaded files in different folders in different files, and the next number and relatively large, direct write path more trouble.

  So, how to deal with this problem? Still need to sort out ideas.

  First, we need according to certain characteristics, find them. For example, we may be in the specified folder, by file name suffix to find the file. Usually, we inquire at the DOS folder to find the file extension in the same time, use the wildcard "*" to replace the file name, for example:.. * Jpg, * xls, and so on. So, we can specify a folder, and then use the wildcard become a regular way to find files matching.

  In addition, if we specified folder, there are cases subfolders, we need a recursive process. That is, after entering the sub-folders, sub-folder object again in the traversal, and so on.

First look at a piece of code:

    private static String generatePattern(String fileConf) {
        fileConf = fileConf.trim ();
         // generate the correct regular configuration according to the 
        fileConf = fileConf.replace ( '*', '#' );
         // . * number plus the previously 
        fileConf = fileConf.replaceAll ( "#", . "*" );
         return fileConf;
    } 

  Here, we define a method to generate regular. Is to "* .XXX" become ". *. XXX" (look carefully, that is, before the addition of a "."). We can use the regular expression to match the file we want to find.

  Next, we look at the problem of recursive search. First, we need to find a definition file folders. In java, we can directly define a main path of the object as a file.

E.g:

        String c = "k:/abc/";
        File file = new File(c);

In this case, use getName () method to get the name of the file or folder (without the upper path). It is also possible to use the listFiles () file or directory object (File class instances) returns under the directory, including hidden files. Of course, for the file, so the operation will return null.

Below, we look at recursive operations. The idea is this:

1. determine the current file object is a file or folder

2. If the file is, if a regular match, the file is added to list.

3. If it is a folder, that folder acquire all of the following file or directory object, if the match is regular, then the file to the list.

    private static ArrayList<File> filePattern(File file, Pattern p) {
        if (file == null) {
            return null;
        }
        // if the file is added fileList 
        IF (file.isFile ()) {
            Matcher fMatcher = p.matcher(file.getName());
            if (fMatcher.matches()) {
                ArrayList<File> list = new ArrayList<File>();
                list.add(file);
                return list;
            }
            // If a directory lookup is performed recursively 
        } the else  IF (file.isDirectory ()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                The ArrayList <File> List = new new the ArrayList <File> ();
                 for (File F: Files) {
                     // here recursively 
                    the ArrayList <File> RLIST = filePattern (F, P);
                     IF (RLIST =! Null ) {
                         / / the search results are added fileList 
                        list.addAll (RLIST);
                    }
                }
                return list;
            }
        }
        return null;
    }

  Well, according to the above code, we can under the path of all the matching files are found regular, and placed in fileList.

  Next, we define a method, using the main path as a parameter and wildcard, to search for documents. In the specified wildcard parameter, we use ";" to separate, to find the documents we need.

E.g:

String dirs = "k:/abc/";
String file_con = "*.doc;*.xls";

  Here there will be a new question, if I have written in accordance with the above, will "k: / abc /" all files that match all find out.

  If I need to find the main path at test1 folder * .doc, and test2 folder * .xls how to do?

  Here in part of the specified parameters, we need to judge the clip file, that last "/" separated process.

Consider the following piece of code:

    public static List<File> getFilesByConf(String dir, String fileConf) {
        String[] fileConfArr = fileConf.split(";");// 多个配置‘;’分开
        List<File> list = new ArrayList<File>();
        if (fileConfArr != null && fileConfArr.length > 0) {
            for (String conftemp : fileConfArr) {
                int at = conftemp.lastIndexOf("/");
                File file = null;
                FileContextPath String = "" ;
                 // absolute directory path 
                String = the contextPath the dir;
                 // processing for the directory section 
                IF (AT> 0 ) {
                    fileContextPath = fileConf.substring(0, at);
                }
                if (StringUtil.isNotEmpty(fileContextPath)) {
                    contextPath = contextPath + fileContextPath;
                }
                file = new File(contextPath);
                String fileNameConf = conftemp.substring(at + 1,conftemp.length());// 文件名配置
                String fileConfTemp = generatePattern(fileNameConf);
                Pattern p = Pattern.compile(fileConfTemp);
                ArrayList<File> listtemp = filePattern(file, p);
                list.addAll(listtemp);
            }
        }
        return removeDuplicate(list);// 去重
    }

  Here, we have completed the process for the path. By the way, here's to heavy use is to use the characteristics of HashSet to go heavy.

    public static List removeDuplicate(List list) {
        if (list == null) {
            return null;
        }
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            Object obj = iter.next();
            if (set.add(obj)) {
                newList.add(obj);
            }
        }
        return newList;
    }

  So far, we have completed the process to find files.

  To summarize, we only need to provide two parameters, one is the main path, a wildcard match string parameters (can take the path), you can find the batch file we need.

  

  Next, we look at the process of downloading files.

  Download the file is usually the better deal, the basic idea is to use the input stream to write, and then save it.

  Note that, for comparing large files, we need to set Buffer (ie, buffer). When the buffer is not applied, each read a byte, a byte is written, since many of the operations of the disk slower than memory, it does not use low efficiency of the buffer; application buffer may be read more than one word Festival, to not written to disk, but placed in memory, to the buffer size when, in written to disk, reducing disk operations, and higher efficiency.

public static boolean writeFile(InputStream is, String filePath) {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fileout;
        try {
            fileout = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        /**
         * Set the buffer size based on actual operating results
         */
        byte[] buffer = new byte[10 * 1024];
        int ch = 0;
        try {
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                is.close();
                fileout.flush();
                fileout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

  Here the actual situation, to set the buffer size.

  This allows the contents of the returned interface, write the file to the specified path.

Guess you like

Origin www.cnblogs.com/generalli2019/p/12247715.html