Java Code Examples for java.io.File#listFiles()

The following examples show how to use java.io.File#listFiles() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SourceFile.java    From jAudioGIT with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * Descend a file hierarchy.  Assumes all children are of type Source files.
 *
 * @see org.multihelp.file.FileNode#traverseFileSystem(java.io.File, int)
 */
public void traverseFileSystem(File root, int depth) {
	if (depth < 512) {
		File[] children = root.listFiles();
		if ((children != null) && (children.length != 0)) {
			for (int i = 0; i < children.length; ++i) {
				if (filter.accept(children[i])) {
					SourceFile childNode = new SourceFile(children[i]);
					this.add(childNode);
					childNode.setParent(this);
					// System.out.println(childNode.toString());
					childNode.traverseFileSystem(children[i], depth + 1);
				}
			}
		}
	}
}
 
Example 2
Source File: FileUtils.java    From wakao-app with MIT License 6 votes vote down vote up
/**
 * 获取目录文件大小
 * 
 * @param dir
 * @return
 */
public static long getDirSize(File dir) {
	if (dir == null) {
		return 0;
	}
	if (!dir.isDirectory()) {
		return 0;
	}
	long dirSize = 0;
	File[] files = dir.listFiles();
	for (File file : files) {
		if (file.isFile()) {
			dirSize += file.length();
		} else if (file.isDirectory()) {
			dirSize += file.length();
			dirSize += getDirSize(file); // 递归调用继续统计
		}
	}
	return dirSize;
}
 
Example 3
Source File: ApiXmlDocWriter.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];
    String pathToDir = s_dirName;

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            addDir(files[i], out);
            continue;
        }
        try(FileInputStream in = new FileInputStream(files[i].getPath());) {
            out.putNextEntry(new ZipEntry(files[i].getPath().substring(pathToDir.length())));
            int len;
            while ((len = in.read(tmpBuf)) > 0) {
                out.write(tmpBuf, 0, len);
            }
            out.closeEntry();
        }catch(IOException ex)
        {
            s_logger.error("addDir:Exception:"+ ex.getMessage(),ex);
        }
    }
}
 
Example 4
Source File: JarMergingTask.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
private void processFolder(JarOutputStream jos, String path, File folder, byte[] buffer) throws IOException {
    for (File file : folder.listFiles()) {
        if (file.isFile()) {
            // new entry
            jos.putNextEntry(new JarEntry(path + file.getName()));

            // put the file content
            FileInputStream fis = new FileInputStream(file);
            int count;
            while ((count = fis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }

            fis.close();

            // close the entry
            jos.closeEntry();
        } else if (file.isDirectory()) {
            processFolder(jos, path + file.getName() + "/", file, buffer);
        }

    }

}
 
Example 5
Source File: AppProperties.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
private List<File> listJobTypeFiles() throws MegatronException {
    String dirStr = globalProps.get(JOB_TYPE_CONFIG_DIR_KEY);
    if (StringUtil.isNullOrEmpty(dirStr)) {
        throw new MegatronException("Job-type config dir not specified in global properties.");
    }
    File file = new File(dirStr);
    File[] files = file.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".properties");
        }
    });
    if (files == null) {
        throw new MegatronException("Cannot list job-type config files in directory: " + file.getAbsolutePath());
    }

    List<File> result = new ArrayList<File>(Arrays.asList(files));
    return result;
}
 
Example 6
Source File: ImageCacher.java    From Ruisi with Apache License 2.0 6 votes vote down vote up
public InputStream getDiskCacheStream(String key) {
    key = hashKeyForDisk(key);
    File f = new File(cacheDir);
    File[] fileList = f.listFiles();
    for (File oldFile : fileList) {
        int position = oldFile.getName().lastIndexOf("_");
        if (position <= 0) {
            continue;
        }
        String name = oldFile.getName().substring(0, position);
        if (name.equals(key)) {
            int count = Integer.parseInt(oldFile.getName().substring(position + 1)) + 1;
            File newFile = new File(cacheDir, name + "_" + count);
            Log.d(TAG, "rename file to " + newFile + " old file is " + oldFile);
            oldFile.renameTo(newFile);
            try {
                return new FileInputStream(newFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
 
Example 7
Source File: Store.java    From rocketmq_trans_message with Apache License 2.0 5 votes vote down vote up
private boolean loadConsumeQueue() {
    File dirLogic = new File(StorePathConfigHelper.getStorePathConsumeQueue(lStorePath));
    File[] fileTopicList = dirLogic.listFiles();
    if (fileTopicList != null) {

        for (File fileTopic : fileTopicList) {
            String topic = fileTopic.getName();

            File[] fileQueueIdList = fileTopic.listFiles();
            if (fileQueueIdList != null) {
                for (File fileQueueId : fileQueueIdList) {
                    int queueId = Integer.parseInt(fileQueueId.getName());
                    ConsumeQueue logic = new ConsumeQueue(
                        topic,
                        queueId,
                        StorePathConfigHelper.getStorePathConsumeQueue(lStorePath),
                        lSize,
                        null);
                    this.putConsumeQueue(topic, queueId, logic);
                    if (!logic.load()) {
                        return false;
                    }
                }
            }
        }
    }
    System.out.printf("load logics queue all over, OK");
    return true;
}
 
Example 8
Source File: DirResourceSet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public Set<String> listWebAppPaths(String path) {
    checkPath(path);
    String webAppMount = getWebAppMount();
    ResourceSet<String> result = new ResourceSet<>();
    if (path.startsWith(webAppMount)) {
        File f = file(path.substring(webAppMount.length()), true);
        if (f != null) {
            File[] list = f.listFiles();
            if (list != null) {
                for (File entry : list) {
                    StringBuilder sb = new StringBuilder(path);
                    if (path.charAt(path.length() - 1) != '/') {
                        sb.append('/');
                    }
                    sb.append(entry.getName());
                    if (entry.isDirectory()) {
                        sb.append('/');
                    }
                    result.add(sb.toString());
                }
            }
        }
    } else {
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        if (webAppMount.startsWith(path)) {
            int i = webAppMount.indexOf('/', path.length());
            if (i == -1) {
                result.add(webAppMount + "/");
            } else {
                result.add(webAppMount.substring(0, i + 1));
            }
        }
    }
    result.setLocked(true);
    return result;
}
 
Example 9
Source File: Cache.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
@WebViewExposed
public static void getFiles(WebViewCallback callback) {
	File[] fileList;
	File cacheDirectory = SdkProperties.getCacheDirectory();

	if (cacheDirectory == null)
		return;

	DeviceLog.debug("Unity Ads cache: checking app directory for Unity Ads cached files");
	FilenameFilter filter = new FilenameFilter() {
		@Override
		public boolean accept(File dir, String filename) {
			return filename.startsWith(SdkProperties.getCacheFilePrefix());
		}
	};

	fileList = cacheDirectory.listFiles(filter);

	if (fileList == null || fileList.length == 0) {
		callback.invoke(new JSONArray());
	}

	try {
		JSONArray files = new JSONArray();

		for(File f : fileList) {
			String name = f.getName().substring(SdkProperties.getCacheFilePrefix().length());
			DeviceLog.debug("Unity Ads cache: found " + name + ", " + f.length() + " bytes");
			files.put(getFileJson(name));
		}

		callback.invoke(files);
	}
	catch (JSONException e) {
		DeviceLog.exception("Error creating JSON", e);
		callback.error(CacheError.JSON_ERROR);
	}
}
 
Example 10
Source File: Files.java    From DKVideoPlayer with Apache License 2.0 5 votes vote down vote up
static List<File> getLruListFiles(File directory) {
    List<File> result = new LinkedList<>();
    File[] files = directory.listFiles();
    if (files != null) {
        result = Arrays.asList(files);
        Collections.sort(result, new LastModifiedComparator());
    }
    return result;
}
 
Example 11
Source File: ExternalStorage.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<String> deploymentMBTilesFilePaths(String deploymentName) {
    List<String> mbtilesFiles = new ArrayList<>();
    File storageDir = Environment.getExternalStorageDirectory();
    File deploymentDir = new File(storageDir, APP_DIR + "/" + DEPLOYMENTS_DIR + "/" + deploymentName);
    File[] files = deploymentDir.listFiles();
    for (File f : files) {
        String ext = FilenameUtils.getExtension(f.getPath());
        if (ext.equals("mbtiles")) {
            mbtilesFiles.add(f.getAbsolutePath());
        }
    }
    return mbtilesFiles;
}
 
Example 12
Source File: CubeSim.java    From SoftwarePilot with MIT License 5 votes vote down vote up
public String driver_movt(String directory)
{
    File CubeDir = new File(directory);
    File[] listOfFiles = CubeDir.listFiles();
    int tx,ty,tz,tgimbal;
    for(File f : listOfFiles){
        try {
            System.out.println(f.getName());
            String cmd = "bash ../externalModels/python/3dPosition/run3d.sh "+directory+"/"+f.getName();
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            tx = Integer.parseInt(in.readLine().split("=")[1]);
            ty = Integer.parseInt(in.readLine().split("=")[1]);
            tz = Integer.parseInt(in.readLine().split("=")[1]);
            tgimbal = Integer.parseInt(in.readLine().split("=")[1]);
            System.out.println(x+" "+y+" "+z+" "+gimbal);
            System.out.println(tx+" "+ty+" "+tz+" "+tgimbal);
            if(x == tx && y == ty && z == tz && (gimbal == -tgimbal || gimbal == tgimbal)){
                return directory + "/"+f.getName();
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }
    System.out.println("Return Null");
    return "";
}
 
Example 13
Source File: ReadXMLFileUtils.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String processListFileTemplate(File fileEntry, String folderParentPath, long groupId, long userId,
		ServiceContext serviceContext) throws PortalException, JAXBException {
	StringBuilder sbTemplateFile = new StringBuilder();
	File[] files = fileEntry.listFiles();
	if (files != null && files.length > 0) {
		sbTemplateFile.append(fileEntry.getName());
		sbTemplateFile.append(ConstantUtils.HTML_NEW_LINE);
		for (File file : files) {
			String fileName = file.getName();
			String subFileName = ImportZipFileUtils.getSubFileName(fileName);
			if (Validator.isNotNull(subFileName)) {
				String filePath = file.getPath();
				String xmlString = convertFiletoString(file);
				DossierTemplate template = convertXMLToDossierTemplate(xmlString);
				boolean flag = ProcessUpdateDBUtils.processUpdateDossierTemplate(template, filePath, folderParentPath, groupId, userId,
						serviceContext);
				if (flag) {
					//Append file success
					sbTemplateFile.append(ConstantUtils.HTML_FOUR_SPACE);
					sbTemplateFile.append(file.getName());
					sbTemplateFile.append(ConstantUtils.HTML_NEW_LINE);
				} else {
					strError = fileEntry.getName() + StringPool.SLASH + fileName;
				}
			}
		}
	}
	return sbTemplateFile.toString();
}
 
Example 14
Source File: AppCacheUtils.java    From v9porn with MIT License 5 votes vote down vote up
private static long getRxcacheFileSizeNum(Context context) {
    long fileSize = 0;
    File file = getRxCacheDir(context);
    for (File childFile : file.listFiles()) {
        fileSize += childFile.length();
    }
    return fileSize;
}
 
Example 15
Source File: BlueMapCLI.java    From BlueMap with MIT License 5 votes vote down vote up
private boolean loadResources() throws IOException, ParseResourceException {
	Logger.global.logInfo("Loading resources ...");

	MainConfig config = configManager.getMainConfig();
	
	File defaultResourceFile = config.getDataPath().resolve("minecraft-client-" + ResourcePack.MINECRAFT_CLIENT_VERSION + ".jar").toFile();
	File resourceExtensionsFile = config.getDataPath().resolve("resourceExtensions.zip").toFile();
	File textureExportFile = config.getWebDataPath().resolve("textures.json").toFile();
	
	if (!defaultResourceFile.exists()) {
		if (!handleMissingResources(defaultResourceFile)) return false;
	}
	
	resourceExtensionsFile.delete();
	FileUtils.copyURLToFile(BlueMapCLI.class.getResource("/resourceExtensions.zip"), resourceExtensionsFile, 10000, 10000);
	
	//find more resource packs
	File resourcePackFolder = configFolder.toPath().resolve("resourcepacks").toFile();
	resourcePackFolder.mkdirs();
	File[] resourcePacks = resourcePackFolder.listFiles();
	Arrays.sort(resourcePacks); //load resource packs in alphabetical order so you can reorder them by renaming
	
	List<File> resources = new ArrayList<>(resourcePacks.length + 1);
	resources.add(defaultResourceFile);
	for (File file : resourcePacks) resources.add(file);
	resources.add(resourceExtensionsFile);
	
	resourcePack = new ResourcePack();
	if (textureExportFile.exists()) resourcePack.loadTextureFile(textureExportFile);
	resourcePack.load(resources);
	resourcePack.saveTextureFile(textureExportFile);
	
	return true;
}
 
Example 16
Source File: FileHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static boolean delete(File toDelete) {
  boolean deleted = true;

  if (toDelete.isDirectory()) {
    File[] children = toDelete.listFiles();
    if (children != null) {
      for (File child : children) {
        deleted &= child.canWrite() && delete(child);
      }
    }
  }

  return deleted && toDelete.canWrite() && toDelete.delete();
}
 
Example 17
Source File: ResourceGroovyMethods.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a directory with all contained files and subdirectories.
 * <p>The method returns
 * <ul>
 * <li>true, when deletion was successful</li>
 * <li>true, when it is called for a non existing directory</li>
 * <li>false, when it is called for a file which isn't a directory</li>
 * <li>false, when directory couldn't be deleted</li>
 * </ul>
 *
 * @param self a File
 * @return true if the file doesn't exist or deletion was successful
 * @since 1.6.0
 */
public static boolean deleteDir(final File self) {
    if (!self.exists())
        return true;
    if (!self.isDirectory())
        return false;

    File[] files = self.listFiles();
    if (files == null)
        // couldn't access files
        return false;

    // delete contained files
    boolean result = true;
    for (File file : files) {
        if (file.isDirectory()) {
            if (!deleteDir(file))
                result = false;
        } else {
            if (!file.delete())
                result = false;
        }
    }

    // now delete directory itself
    if (!self.delete())
        result = false;

    return result;
}
 
Example 18
Source File: HtmlLoggingListenerTest.java    From webtester-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testThatLogFileIsNotCreatedIfNoRelevantEventsWereLogged() throws IOException {

    cut.eventOccurred(irrelevantEvent());
    cut.eventOccurred(irrelevantEvent());

    File folder = tempFolder.getRoot();
    cut.saveToFolder(folder);
    File[] files = folder.listFiles();
    assertThat(files.length, is(0));

}
 
Example 19
Source File: DistributedCacheLookupUDF.java    From incubator-hivemall with Apache License 2.0 4 votes vote down vote up
private static void loadValues(Object2ObjectMap<Object, Object> map, File file,
        PrimitiveObjectInspector keyOI, PrimitiveObjectInspector valueOI)
        throws IOException, SerDeException {
    if (!file.exists()) {
        return;
    }
    if (!file.getName().endsWith(".crc")) {
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                loadValues(map, f, keyOI, valueOI);
            }
        } else {
            LazySimpleSerDe serde = HiveUtils.getKeyValueLineSerde(keyOI, valueOI);
            StructObjectInspector lineOI = (StructObjectInspector) serde.getObjectInspector();
            StructField keyRef = lineOI.getStructFieldRef("key");
            StructField valueRef = lineOI.getStructFieldRef("value");
            PrimitiveObjectInspector keyRefOI =
                    (PrimitiveObjectInspector) keyRef.getFieldObjectInspector();
            PrimitiveObjectInspector valueRefOI =
                    (PrimitiveObjectInspector) valueRef.getFieldObjectInspector();

            BufferedReader reader = null;
            try {
                reader = HadoopUtils.getBufferedReader(file);
                String line;
                while ((line = reader.readLine()) != null) {
                    Text lineText = new Text(line);
                    Object lineObj = serde.deserialize(lineText);
                    List<Object> fields = lineOI.getStructFieldsDataAsList(lineObj);
                    Object f0 = fields.get(0);
                    Object f1 = fields.get(1);
                    Object k = keyRefOI.getPrimitiveJavaObject(f0);
                    Object v = valueRefOI.getPrimitiveWritableObject(valueRefOI.copyObject(f1));
                    map.put(k, v);
                }
            } finally {
                IOUtils.closeQuietly(reader);
            }
        }
    }
}
 
Example 20
Source File: ExportMapOpTest.java    From mrgeo with Apache License 2.0 4 votes vote down vote up
@Test
@Category(UnitTest.class)
public void exportOneTile() throws IOException
{
  String output = testUtils.getOutputLocalFor(onetile);

  MrsImageDataProvider dp = DataProviderFactory.getMrsImageDataProvider(onetilePath.toString(),
      DataProviderFactory.AccessMode.READ, new ProviderProperties());

  RasterMapOp mapop = MrsPyramidMapOp.apply(dp);
  mapop.context(localContext);
//  def create(raster:RasterMapOp, name:String, singleFile:Boolean = false, zoom:Int = -1, numTiles:Int = -1,
//    mosaic:Int = -1, format:String = "tif", randomTiles:Boolean = false,
//    tms:Boolean = false, colorscale:String = "", tileids:String = "",
//    bounds:String = "", allLevels:Boolean = false, overridenodata:Double = Double.NegativeInfinity):MapOp = {

  MapOp exportmapop = ExportMapOp.create(mapop, output,
      false, -1, "", -1, -1, "tif", false, false, "", "", "", false,
      Double.NEGATIVE_INFINITY);  // this line is all defaults.

  exportmapop.execute(localContext);

  File parent = new File(output).getParentFile();
  File[] files = parent.listFiles();
  Assert.assertNotNull("No files exported", files);
  // should be the image and a .<image>.crc file created locally
  Assert.assertEquals("Wrong number of files exported", 2, files.length);

  String name;
  if (files[0].getCanonicalPath().endsWith(".tif"))
  {
    name = files[0].getCanonicalPath();
  }
  else
  {
    name = files[1].getCanonicalPath();
  }
  Dataset gdal = GDALUtils.open(name);
  MrGeoRaster exported = MrGeoRaster.fromDataset(gdal);

  testUtils.compareRasters(testname.getMethodName(), exported);
}