canonical example by Tabnine
public long getDirectorySize(File file) { if (!file.exists()) { return 0; } if (file.isFile()) { return file.length(); } File[] files; if (!file.isDirectory() || (files = file.listFiles()) == null) { return 0; } return Arrays.stream(files).mapToLong(f -> getDirectorySize(f)).sum(); }
canonical example by Tabnine
public void zipFile(File srcFile, File zipFile) throws IOException { try (FileInputStream fis = new FileInputStream(srcFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) { zos.putNextEntry(new ZipEntry(srcFile.getName())); int len; byte[] buffer = new byte[1024]; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); } }
public static void cpdir(File src, File dest) throws BrutException { dest.mkdirs(); File[] files = src.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; File destFile = new File(dest.getPath() + File.separatorChar + file.getName()); if (file.isDirectory()) { cpdir(file, destFile); continue; } try { InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } catch (IOException ex) { throw new BrutException("Could not copy file: " + file, ex); } } }
private void copyAndReplace (String outputDir, Project project, Map<String, String> values) { File out = new File(outputDir); if (!out.exists() && !out.mkdirs()) { throw new RuntimeException("Couldn't create output directory '" + out.getAbsolutePath() + "'"); } for (ProjectFile file : project.files) { copyFile(file, out, values); } }
void deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles()) deleteRecursive(child); fileOrDirectory.delete(); }
public class DownloadTask extends GroundyTask { public static final String PARAM_URL = "com.groundy.sample.param.url"; @Override protected boolean doInBackground() { try { String url = getParameters().getString(PARAM_URL); File dest = new File(getContext().getFilesDir(), new File(url).getName()); DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this)); return true; } catch (Exception pokemon) { return false; } } }
File f = new File(filePathString); if(f.exists() && !f.isDirectory()) { // do something }
@Test public void testDecompressBzip2() throws IOException { final File tmpDir = temporaryFolder.newFolder("testDecompressBzip2"); final File bzFile = new File(tmpDir, testFile.getName() + ".bz2"); Assert.assertFalse(bzFile.exists()); try (final OutputStream out = new BZip2CompressorOutputStream(new FileOutputStream(bzFile))) { ByteStreams.copy(new FileInputStream(testFile), out); } try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(bzFile), bzFile.getName())) { assertGoodDataStream(inputStream); } }
/** * Returns the URLs in the class path specified by the {@code java.class.path} {@linkplain * System#getProperty system property}. */ @VisibleForTesting // TODO(b/65488446): Make this a public API. static ImmutableList<URL> parseJavaClassPath() { ImmutableList.Builder<URL> urls = ImmutableList.builder(); for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) { try { try { urls.add(new File(entry).toURI().toURL()); } catch (SecurityException e) { // File.toURI checks to see if the file is a directory urls.add(new URL("file", null, new File(entry).getAbsolutePath())); } } catch (MalformedURLException e) { logger.log(WARNING, "malformed classpath entry: " + entry, e); } } return urls.build(); }
private void writeZone(File outputDir, DateTimeZoneBuilder builder, DateTimeZone tz) throws IOException { if (ZoneInfoLogger.verbose()) { System.out.println("Writing " + tz.getID()); } File file = new File(outputDir, tz.getID()); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(file); try { builder.writeTo(tz.getID(), out); } finally { out.close(); } // Test if it can be read back. InputStream in = new FileInputStream(file); DateTimeZone tz2 = DateTimeZoneBuilder.readFrom(in, tz.getID()); in.close(); if (!tz.equals(tz2)) { System.out.println("*e* Error in " + tz.getID() + ": Didn't read properly from file"); } }
@Test public void testCanRead() throws Exception { final File readOnlyFile = new File(getTestDirectory(), "read-only-file1.txt"); if (!readOnlyFile.getParentFile().exists()) { throw new IOException("Cannot create file " + readOnlyFile + " as the parent directory does not exist"); } try (final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(readOnlyFile))){ TestUtils.generateTestData(output, 32); } readOnlyFile.setReadOnly(); assertFiltering(CanReadFileFilter.CAN_READ, readOnlyFile, true); assertFiltering(CanReadFileFilter.CANNOT_READ, readOnlyFile, false); assertFiltering(CanReadFileFilter.READ_ONLY, readOnlyFile, true); readOnlyFile.delete(); }
private File extractFile (String sourcePath, String sourceCrc, File extractedFile) throws IOException { String extractedCrc = null; if (extractedFile.exists()) { try { extractedCrc = crc(new FileInputStream(extractedFile)); } catch (FileNotFoundException ignored) { try { input = readFile(sourcePath); extractedFile.getParentFile().mkdirs(); output = new FileOutputStream(extractedFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); throw new GdxRuntimeException("Error extracting file: " + sourcePath + "\nTo: " + extractedFile.getAbsolutePath(), ex); } finally {
final ZipEntry entry, final String name) throws IOException { File file = new File(destDir, name); files.add(file); if (entry.isDirectory()) { OutputStream out = null; try { in = new BufferedInputStream(zip.getInputStream(entry)); out = new BufferedOutputStream(new FileOutputStream(file)); byte buffer[] = new byte[BUFFER_LEN]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); in.close(); out.close();
@AndroidIncompatible // Android forbids null parent ClassLoader public void testClassPathEntries_URLClassLoader_noParent() throws Exception { URL url1 = new URL("file:/a"); URL url2 = new URL("file:/b"); URLClassLoader classloader = new URLClassLoader(new URL[] {url1, url2}, null); assertThat(ClassPath.Scanner.getClassPathEntries(classloader)) .containsExactly(new File("/a"), classloader, new File("/b"), classloader); }
public void chop() { File targetFile = new File(txnLogFile.getParentFile(), txnLogFile.getName() + ".chopped" + zxid); try ( InputStream is = new BufferedInputStream(new FileInputStream(txnLogFile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(targetFile)) ) { if (!LogChopper.chop(is, os, zxid)) { throw new TxnLogToolkitException(ExitCode.INVALID_INVOCATION.getValue(), "Failed to chop %s", txnLogFile.getName()); } } catch (Exception e) { System.out.println("Got exception: " + e.getMessage()); } }
// Assume block needs to be inside a Try/Catch block. String path = Environment.getExternalStorageDirectory().toString(); OutputStream fOut = null; Integer counter = 0; File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten. fOut = new FileOutputStream(file); Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate fOut.flush(); // Not really required fOut.close(); // do not forget to close the stream MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
File folder = new File("your/path"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { System.out.println("File " + listOfFiles[i].getName()); } else if (listOfFiles[i].isDirectory()) { System.out.println("Directory " + listOfFiles[i].getName()); } }
/** * {@inheritDoc} */ public Manifest getManifest() throws IOException { File file = new File(folder, JarFile.MANIFEST_NAME); if (file.exists()) { InputStream inputStream = new FileInputStream(file); try { return new Manifest(inputStream); } finally { inputStream.close(); } } else { return NO_MANIFEST; } }
public static void copyFile(InputStream from, File to) throws IOException { if (! to.getParentFile().exists()) { to.getParentFile().mkdirs(); } try (OutputStream os = new FileOutputStream(to)) { byte[] buffer = new byte[65536]; int count = from.read(buffer); while (count > 0) { os.write(buffer, 0, count); count = from.read(buffer); } } }