以文件的方式扫描包下的所有Class文件
975469
private void doScanPackageClassesByFile(Set<Class<?>> classes,
                                            String packageName, String packagePath, boolean recursive) {
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        final boolean fileRecursive = recursive;
        File[] dirfiles = dir.listFiles(new FileFilter() {
            // 自定义文件过滤规则
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return fileRecursive;
                }
                String filename = file.getName();
                return !(excludeInner && filename.indexOf('$') != -1) && filterClassName(filename);
            }
        });
        for (File file : dirfiles) {
            if (file.isDirectory()) {
                doScanPackageClassesByFile(classes, packageName + "."
                        + file.getName(), file.getAbsolutePath(), recursive);
            } else {
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    classes.add(Thread.currentThread().getContextClassLoader()
                            .loadClass(packageName + '.' + className));

                } catch (ClassNotFoundException e) {
                    throw new LtsRuntimeException(e);
                }
            }
        }
    }
212974
public static function all()
    {
        $command = 'grep --include="*.php" --files-with-matches -r "class" '.app_path();

        exec($command, $files);

        return collect($files)->map(function($file) {
            return self::convertFileToClass($file);
        })->filter(function($class) {
            return class_exists($class) && is_subclass_of($class, Model::class);
        });
    }
1184747
function (file) {

        var that = this;
        var error = false;
        var walk;

        if (file) {


            var fileList = typeof file === 'string' ? [file] : file;

            fileList = fileList.map(function (file) {
                return path.resolve(that.base, file);
            });

            walk = function (list) {

                list.forEach(function (file) {

                    if (error) {
                        return;
                    }

                    error = !that._compile(file);

                });
            };


            walk(fileList);

            if (!error && this.options.combo) {
                this._combo();
            }

        } else {


            walk = function (dir) {

                if (dir === that.output) {
                    return;
                }

                var dirList = fs.readdirSync(dir);

                dirList.forEach(function (item) {

                    if (error) {
                        return;
                    }

                    if (fs.statSync(path.join(dir, item)).isDirectory()) {
                        walk(path.join(dir, item));
                    } else if (that.filterBasename(item) && that.filterExtname(item)) {
                        error = !that._compile(path.join(dir, item));
                    }

                });
            };


            walk(this.base);

            if (!error && this.options.combo) {
                this._combo();
            }
        }

    }
275128
function walk(dir, doneFn) {
    fs.readdir(dir, (err, list) => {
      if (err) return doneFn(err);

      list.forEach((file) => {
        // img图片不部署，使用七牛云单独存储
        if (path.basename(dir) === options.outputDir && file === 'img') return;

        file = path.resolve(dir, file);

        fs.stat(file, (eror, stats) => {
          if (eror) return doneFn(err);

          const isFile = stats.isFile(); // 是文件
          const isDir = stats.isDirectory(); // 是文件夹

          if (isFile) {
            return doneFn(null, file);
          }
          if (isDir) {
            walk(file, doneFn); // 递归，如果是文件夹，就继续遍历该文件夹下面的文件
          }
        });
      });
    });
  }
1252250
public static JarClassLoader load(File dir) {
		final JarClassLoader loader = new JarClassLoader();
		loader.addJar(dir);//查找加载所有jar
		loader.addURL(dir);//查找加载所有class
		return loader;
	}
687280
function getPublishFile(selectedFile) {
        console.log('你需要发布文件如下：');
        
        var files = [];
        selectedFile.forEach(function(file, idx) {
            console.log('  [' + (idx + 1) + ']' + file);
            files.push(file);
        });
        
        prepareBatchPubFiles(awpConfig, pubConfig, files);

    }
386218
public function getDefinitions()
    {

        // 获取扫描的PHP文件
        $classNames     = $this->registerLoaderAndScanBean();
        $fileClassNames = $this->scanFilePhpClass();
        $classNames     = array_merge($classNames, $fileClassNames);

        foreach ($classNames as $className) {
            $this->parseBeanAnnotations($className);
        }
        $this->parseAnnotationsData();

        return $this->definitions;
    }
1308052
def _RealGetContents(self):
        """"""
        fp = self.fp
        try:
            endrec = _EndRecData(fp)
        except OSError:
            raise BadZipFile("File is not a zip file")
        if not endrec:
            raise BadZipFile("File is not a zip file")
        if self.debug > 1:
            print(endrec)
        size_cd = endrec[_ECD_SIZE]             # bytes in central directory
        offset_cd = endrec[_ECD_OFFSET]         # offset of central directory
        self._comment = endrec[_ECD_COMMENT]    # archive comment

        # ---> APK文件只有一个，不可能存在额外数据。
        # "concat" is zero, unless zip was concatenated to another file
        # concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
        # if endrec[_ECD_SIGNATURE] == stringEndArchive64:
        #     # If Zip64 extension structures are present, account for them
        #     concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
        concat = 0

        if self.debug > 2:
            inferred = concat + offset_cd
            print("given, inferred, offset", offset_cd, inferred, concat)
        # self.start_dir:  Position of start of central directory
        self.start_dir = offset_cd + concat
        fp.seek(self.start_dir, 0)
        data = fp.read(size_cd)
        fp = io.BytesIO(data)
        total = 0
        while total < size_cd:
            centdir = fp.read(sizeCentralDir)
            if len(centdir) != sizeCentralDir:
                raise BadZipFile("Truncated central directory")
            centdir = struct.unpack(structCentralDir, centdir)
            if centdir[_CD_SIGNATURE] != stringCentralDir:
                raise BadZipFile("Bad magic number for central directory")
            if self.debug > 2:
                print(centdir)
            filename = fp.read(centdir[_CD_FILENAME_LENGTH])
            flags = centdir[5]
            if flags & 0x800:
                # UTF-8 file names extension
                filename = filename.decode('utf-8')
            else:
                # Historical ZIP filename encoding
                filename = filename.decode('cp437')
            # Create ZipInfo instance to store file information
            x = ZipInfo(filename)
            x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
            x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
            x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
            (x.create_version, x.create_system, x.extract_version, x.reserved,
             x.flag_bits, x.compress_type, t, d,
             x.CRC, x.compress_size, x.file_size) = centdir[1:12]
            if x.extract_version > MAX_EXTRACT_VERSION:
                raise NotImplementedError("zip file version %.1f" %
                                          (x.extract_version / 10))
            x.volume, x.internal_attr, x.external_attr = centdir[15:18]
            # Convert date/time code to (year, month, day, hour, min, sec)
            x._raw_time = t
            x.date_time = ((d >> 9) + 1980, (d >> 5) & 0xF, d & 0x1F,
                           t >> 11, (t >> 5) & 0x3F, (t & 0x1F) * 2)

            x._decodeExtra()
            # x.header_offset = x.header_offset + concat
            self.filelist.append(x)
            self.NameToInfo[x.filename] = x

            # update total bytes read from central directory
            total = total + sizeCentralDir + \
                centdir[_CD_FILENAME_LENGTH] + \
                centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]
274320
public Collection<String> scanClasses() {
        return scanJar(p -> Files.isRegularFile(p) && p.toString().endsWith(".class") && !isIgnored(p.toAbsolutePath()));
    }
34996
@Override
    public AttachedFile[] getFiles(String CorpNum, MgtKeyType KeyType,
                                   String MgtKey) throws PopbillException {
        if (KeyType == null)
            throw new PopbillException(-99999999, "관리번호형태가 입력되지 않았습니다.");
        if (MgtKey == null || MgtKey.isEmpty())
            throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");

        return httpget("/Taxinvoice/" + KeyType.name() + "/" + MgtKey
                + "/Files", CorpNum, null, AttachedFile[].class);
    }
456741
protected final void loadAllClass(List<File> jarFiles) throws Exception 
	{
		if (state == State.loading) 
		{
			return;
		}
		rwLock.writeLock().lock();
		try {
			state = State.loading;
			//复制文件到临时目录,因为urlClassLoader加载后会占用文件,导致后续无法删除scriptLibDir下的文件
			List<MirrorFile> waiteLoad=copyToTmpDir(jarFiles);
			ScriptClassLoader newClassLoader = new ScriptClassLoader();
			Map<String, RecordFile> newLoadedRecord = new HashMap<String, RecordFile>();
			Set<Class<?>> allClass = new HashSet<Class<?>>();
			for (MirrorFile mf : waiteLoad) 
			{
				File file=mf.getFile();
				File mirrorFile=mf.getMirrorFile();
				//使用镜像文件加载进classLoader
				Set<Class<?>> jarClass = loadAllClass(mirrorFile, newClassLoader);
				allClass.addAll(jarClass);
				//记录文件变化,使用源文件的修改时间
				RecordFile rf = new RecordFile(file.getPath());
				rf.setLastModifyTime(file.lastModified());
				newLoadedRecord.put(rf.getFilePath(), rf);
				_log.debug("加载jar文件" + rf.getFilePath() + ",class数量:" + jarClass.size() + ",class:" + jarClass.toString());
			}
			Map<Integer, Class<? extends T>> newCodeMap = findScriptCodeMap(findScriptClass(allClass));
			this.codeMap.clear();
			this.loadedRecord.clear();
			this.classLoader.close();
			this.codeMap.putAll(newCodeMap);
			this.loadedRecord.putAll(newLoadedRecord);
			this.classLoader = newClassLoader;
			this.classLoader.close();
		} finally {
			state = State.loaded;
			rwLock.writeLock().unlock();
		}
	}
303153
private static List<String> load(String path) {
        List<String> result = new ArrayList<>();
        try{
            InputStream in = null;
            LOGGER.info("加载资源："+path);
            if(path.startsWith("classpath:")){
                in = AutoDetector.class.getClassLoader().getResourceAsStream(path.replace("classpath:", ""));
            }else{
                in = new FileInputStream(path);
            }
            try(BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"))){
                String line;
                while((line = reader.readLine()) != null){
                    line = line.trim();
                    if("".equals(line) || line.startsWith("#")){
                        continue;
                    }
                    result.add(line);
                }
            }
        }catch(Exception e){
            LOGGER.error("加载资源失败："+path, e);
        }
        return result;
    }
789795
function (path) {
    let classes = [];

    let files = fs.readdirSync(path);
    for (let i = 0; i < files.length; i++) {
      let clazz = require(path + '/' + files[i]);
      classes.push(clazz);
    }

    return classes;
  }
475484
private static void watchFile(final File file, ResourceLoader resourceLoader, String resourcePaths) {
        LOGGER.info("监控文件："+file.toString());
        DirectoryWatcher.WatcherCallback watcherCallback = new DirectoryWatcher.WatcherCallback(){
            private long lastExecute = System.currentTimeMillis();
            @Override
            public void execute(WatchEvent.Kind<?> kind, String path) {
                if(System.currentTimeMillis() - lastExecute > 1000){
                    lastExecute = System.currentTimeMillis();
                    if(!path.equals(file.toString())){
                        return;
                    }
                    LOGGER.info("事件："+kind.name()+" ,路径："+path);
                    synchronized(AutoDetector.class){
                        DirectoryWatcher dw = WATCHER_CALLBACKS.get(this);
                        String paths = RESOURCES.get(dw);
                        ResourceLoader loader = RESOURCE_LOADERS.get(dw);
                        LOGGER.info("重新加载数据");
                        loadAndWatch(loader, paths);
                    }
                }
            }

        };
        DirectoryWatcher fileWatcher = DirectoryWatcher.getDirectoryWatcher(watcherCallback,
                StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE);
        fileWatcher.watchDirectory(file.getParent());
        WATCHER_CALLBACKS.put(watcherCallback, fileWatcher);
        RESOURCES.put(fileWatcher, resourcePaths);
        RESOURCE_LOADERS.put(fileWatcher, resourceLoader);
    }
41928
def _load_class_names(self, filename, dirname):
        
        full_path = osp.join(dirname, filename)
        classes = []
        with open(full_path, 'r') as f:
            classes = [l.strip() for l in f.readlines()]
        return classes
1339249
private List<String> readFile(File file) throws Exception {
        List<String> content = new ArrayList<>(100);
        try (BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
            String line;
            while ((line = is.readLine()) != null) {
                content.add(line);
            }
            return content;
        }
    }
1129722
private void initScriptClasses(Set<Class<?>> classes)throws Exception
	{
		ClassRegister classRegister=new ClassRegister();
		for (Class<?> clazz : classes) {
			onClassFind(clazz, classRegister);
		}
		Set<Class<? extends S>> scriptClass=findScriptClass(classes);
		Set<Class<? extends S>> instanceAbleScript = findInstanceAbleScript(scriptClass);
		for(Class<? extends S> clazz:instanceAbleScript)
		{
			onScriptClassFind(clazz, classRegister);//交给子类处理
		}
		ClassData cd=new ClassData();
		cd.intMap.putAll(classRegister.intMap);
		cd.stringMap.putAll(classRegister.stringMap);
		_log.info("loadScriptClass complete,id mapping size:"+cd.intMap.size()+",name mapping size:"+cd.stringMap.size());
		this.classData=cd;
	}