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 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 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()); } }
@Override public boolean accept(File pathname) { return pathname.isDirectory() && !existing.contains(pathname.getName()); } })) {
/** * Subclassing this function is intended to provide custom open behaviour on a per-file basis. */ protected @SQLiteOpenOptions int determineOpenOptions(File databaseFile) { @SQLiteOpenOptions int flags = 0; // Try to guess if we should be using write-ahead logging. If this heuristic fails // developers are expected to subclass this provider and explicitly assert the connection. File walFile = new File(databaseFile.getParent(), databaseFile.getName() + "-wal"); if (walFile.exists()) { flags |= SQLiteDatabaseCompat.ENABLE_WRITE_AHEAD_LOGGING; } return flags; }
/** * @param fromFile * @param toPath * @param fileCopyProcessor */ private static void copyFileToPath(final String fromFile, final String toPath, final FileCopyProcessor fileCopyProcessor) { File from = new File(fromFile); File to = new File(toPath); if (from.exists() && from.isFile()) { createDirectory(toPath); String tempFromFile = from.getAbsolutePath(); String tempToFile = to.getAbsolutePath() + File.separator + from.getName(); copyFileToFile(tempFromFile, tempToFile, fileCopyProcessor); } }
private static void validateCreateOutputDir(File dir) { if (!dir.exists()) { dir.mkdirs(); } if (!dir.canWrite()) { throw new IllegalStateException(dir.getName() + " does not have write permissions."); } if (!dir.isDirectory()) { throw new IllegalStateException(dir.getName() + " is not a directory."); } }
// 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());
String path = Environment.getExternalStorageDirectory().toString()+"/Pictures"; Log.d("Files", "Path: " + path); File directory = new File(path); File[] files = directory.listFiles(); Log.d("Files", "Size: "+ files.length); for (int i = 0; i < files.length; i++) { Log.d("Files", "FileName:" + files[i].getName()); }
private URLClassLoader buildClassLoader(String plugin) throws Exception { File file = new File(plugin); if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) { return buildClassLoaderFromPom(file); } if (file.isDirectory()) { return buildClassLoaderFromDirectory(file); } return buildClassLoaderFromCoordinates(plugin); }
/** * @param output unsigned apk file output * @throws IOException */ private void generateUnsignedApk(File output) throws IOException { Logger.d("Generate unsigned apk: %s", output.getName()); final File tempOutDir = config.mTempResultDir; if (!tempOutDir.exists()) { throw new IOException(String.format( "Missing patch unzip files, path=%s\n", tempOutDir.getAbsolutePath())); } FileOperation.zipInputDir(tempOutDir, output, null); if (!output.exists()) { throw new IOException(String.format( "can not found the unsigned apk file path=%s", output.getAbsolutePath())); } }
private void unzipApkFile(File file, File destFile) throws TinkerPatchException, IOException { String apkName = file.getName(); if (!apkName.endsWith(TypedValue.FILE_APK)) { throw new TinkerPatchException( String.format("input apk file path must end with .apk, yours %s\n", apkName) ); } String destPath = destFile.getAbsolutePath(); Logger.d("UnZipping apk to %s", destPath); FileOperation.unZipAPk(file.getAbsoluteFile().getAbsolutePath(), destPath); }
/** * Filter the file rules * * @param file * @param recursive * @return */ private File[] accept(File file, final boolean recursive) { // Custom filtering rules If you can loop (include subdirectories) or is the end of the file. Class (compiled java class file) return file.listFiles(file1 -> (recursive && file1.isDirectory()) || (file1.getName().endsWith(".class"))); }
void check(String baseClassName) throws Exception { File f = directoryOf(baseClassName); if (f == null) { return; } StringBuilder e = new StringBuilder(); File[] files = f.listFiles(); if (files != null) { for (File g : files) { if (g.getName().startsWith(baseClassName) && g.getName().endsWith(".java")) { String className = "io.reactivex.internal.operators." + baseClassName.toLowerCase() + "." + g.getName().replace(".java", ""); Class<?> clazz = Class.forName(className); if ((clazz.getModifiers() & Modifier.FINAL) == 0 && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) { e.append("java.lang.RuntimeException: ").append(className).append(" is not final\r\n"); e.append(" at ").append(className).append(" (").append(g.getName()).append(":14)\r\n\r\n"); } } } } if (e.length() != 0) { System.out.println(e); throw new AssertionError(e.toString()); } }
public void cleanupFiles() { for (File file : mContext.getFilesDir().listFiles()) { if (file.getName().startsWith(FILENAME_PREFIX)) { if (!file.delete()) { LogRedirector.w(TAG, "Failed to delete " + file.getAbsolutePath()); } } } LogRedirector.i(TAG, "Cleaned up temporary network files."); }
private static List<JavaFileObject> browseDir(String packageName, File directory) { List<JavaFileObject> result = new ArrayList<>(); for (File childFile : directory.listFiles()) { if (childFile.isFile() && childFile.getName().endsWith(CLASS_FILE)) { String binaryName = packageName + "." + childFile.getName().replaceAll(CLASS_FILE + "$", ""); result.add(new CustomJavaFileObject(childFile.toURI(), JavaFileObject.Kind.CLASS, binaryName)); } } return result; }
public void listFilesForFolder(final File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); } else { System.out.println(fileEntry.getName()); } } } final File folder = new File("/home/you/Desktop"); listFilesForFolder(folder);
private List<File> compileClass(Class<?> cls) throws IOException { String fileName = cls.getName(); int end = fileName.indexOf('$'); if (end != -1) { fileName = fileName.substring(0, end); } fileName = fileName.replace('.', '/') + ".java"; File file = new File(TEST_DIRECTORY, fileName); if (!file.exists()) { file = new File(TEST_DIRECTORY2, fileName); } assertThat("Test source file not found: " + fileName, file.exists(), is(true)); List<File> compileFileList = Collections.singletonList(file); File outTmp = createTempDir("jadx-tmp-classes"); outTmp.deleteOnExit(); List<File> files = StaticCompiler.compile(compileFileList, outTmp, withDebugInfo); // remove classes which are parents for test class files.removeIf(next -> !next.getName().contains(cls.getSimpleName())); for (File clsFile : files) { clsFile.deleteOnExit(); } return files; }