Tabnine Logo
FileUtils
Code IndexAdd Tabnine to your IDE (free)

How to use
FileUtils
in
org.apache.commons.io

Best Java code snippets using org.apache.commons.io.FileUtils (Showing top 20 results out of 31,131)

Refine searchRefine arrow

  • IOUtils
  • Path
  • FileOutputStream
  • Paths
  • Files
  • FileInputStream
  • BufferedOutputStream
  • OutputStream
  • InputStream
origin: apache/incubator-druid

 @Override
 protected void cleanup(
   Context context
 ) throws IOException
 {
  final String tmpDirLoc = context.getConfiguration().get(TMP_FILE_LOC_KEY);
  final File tmpDir = Paths.get(tmpDirLoc).toFile();
  FileUtils.deleteDirectory(tmpDir);
  context.progress();
  context.setStatus("Clean");
 }
}
origin: apache/storm

private void readVersion() throws IOException {
  Path versionFile = topologyBasicBlobsRootDir.resolve(type.getVersionFileName());
  if (!fsOps.fileExists(versionFile)) {
    version = NOT_DOWNLOADED_VERSION;
  } else {
    String ver = FileUtils.readFileToString(versionFile.toFile(), "UTF8").trim();
    version = Long.parseLong(ver);
  }
}
origin: internetarchive/heritrix3

/**
 * create a new job dir and copy profile CXML into as non-profile CXML
 * @param newJobDir new job directory
 */
public boolean createNewJobWithDefaults(File newJobDir) {
  try {
    // get crawler-beans template into string
    InputStream inStream = getProfileCxmlResource();
    String defaultCxmlStr;
    defaultCxmlStr = IOUtils.toString(inStream);
    inStream.close();
    // write default crawler-beans string to new job dir
    org.archive.util.FileUtils.ensureWriteableDirectory(newJobDir);
    File newJobCxml = new File(newJobDir,"crawler-beans.cxml");
    FileUtils.writeStringToFile(newJobCxml, defaultCxmlStr);
    return true;
  } catch (IOException e) {
    LOGGER.log(Level.SEVERE,"failed to create new job: "
        + newJobDir.getAbsolutePath());
    return false;
  }
}
origin: alibaba/canal

public void cleanDir() throws IOException {
  File destDirFile = new File(destDir);
  FileUtils.forceMkdir(destDirFile);
  FileUtils.cleanDirectory(destDirFile);
}
origin: apache/incubator-druid

TmpFileSegmentWriteOutMedium(File outDir) throws IOException
{
 File tmpOutputFilesDir = new File(outDir, "tmpOutputFiles");
 FileUtils.forceMkdir(tmpOutputFilesDir);
 closer.register(() -> FileUtils.deleteDirectory(tmpOutputFilesDir));
 this.dir = tmpOutputFilesDir;
}
origin: gocd/gocd

private void cleanupTempFiles() {
  FileUtils.deleteQuietly(new File(FileUtil.TMP_PARENT_DIR));
  FileUtils.deleteQuietly(new File("exploded_agent_launcher_dependencies")); // launchers extracted from old versions
  FileUtils.listFiles(new File("."), AGENT_LAUNCHER_TMP_FILE_FILTER, FalseFileFilter.INSTANCE).forEach(FileUtils::deleteQuietly);
  FileUtils.deleteQuietly(new File(new SystemEnvironment().getConfigDir(), "trust.jks"));
}
origin: alibaba/jstorm

  Collection<File> files = FileUtils.listFiles(new File(jstormClientContext.hadoopConfDir), new String[]{JOYConstants.XML}, true);
  for (File file : files) {
    LOG.info("adding hadoop conf file to conf: " + file.getAbsolutePath());
String jarShellScriptPath = jarPath + JOYConstants.START_JSTORM_SHELL;
try {
  InputStream stream = new FileInputStream(jarShellScriptPath);
  FileOutputStream out = new FileOutputStream(JOYConstants.START_JSTORM_SHELL);
  out.write(IOUtils.toByteArray(stream));
  out.close();
  jstormClientContext.shellScriptPath = JOYConstants.START_JSTORM_SHELL;
} catch (Exception e) {
origin: alibaba/canal

FileUtils.forceMkdir(parentFile);
FileOutputStream fos = null;
try {
        bos = new BufferedOutputStream(new FileOutputStream(tarFile));
        int read = -1;
        byte[] buffer = new byte[1024];
        while ((read = tais.read(buffer)) != -1) {
          bos.write(buffer, 0, read);
        IOUtils.closeQuietly(bos);
      fos = new FileOutputStream(file);
      byte[] buffer = new byte[1024];
      int len;
      long nextPrintProgress = 0;
      logger.info("start to download file " + file.getName());
      while ((len = is.read(buffer)) != -1) {
        fos.write(buffer, 0, len);
        copySize += len;
      fos.flush();
    } finally {
      IOUtils.closeQuietly(fos);
  IOUtils.closeQuietly(fos);
origin: io.teecube.t3/t3-common

/**
 * Add all files from the source directory to the destination zip file.
 *
 * @param source      the directory with files to add
 * @param destination the zip file that should contain the files
 * @throws IOException      if the io fails
 * @throws ArchiveException if creating or adding to the archive fails
 */
public static void addFilesToZip(File source, File destination) throws IOException, ArchiveException {
  OutputStream archiveStream = new FileOutputStream(destination);
  ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);
  Collection<File> fileList = org.apache.commons.io.FileUtils.listFiles(source, null, true);
  for (File file : fileList) {
    String entryName = getEntryName(source, file);
    ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
    archive.putArchiveEntry(entry);
    BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
    IOUtils.copy(input, archive);
    input.close();
    archive.closeArchiveEntry();
  }
  archive.finish();
  archiveStream.close();
}
origin: apache/incubator-pinot

final List<File> untaredFiles = new LinkedList<File>();
try {
 is = new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(inputFile)));
 debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
 TarArchiveEntry entry = null;
    FileUtils.deleteDirectory(outputFile);
    outputFileStream = new FileOutputStream(outputFile);
    IOUtils.copy(debInputStream, outputFileStream);
   } finally {
    IOUtils.closeQuietly(outputFileStream);
 IOUtils.closeQuietly(debInputStream);
 IOUtils.closeQuietly(is);
origin: simpligility/android-maven-plugin

FileUtils.deleteQuietly( aarLibrary );
    if ( mergedConsumerProguardFile.exists() )
      FileUtils.forceDelete( mergedConsumerProguardFile );
        try
          consumerProguardFileInputStream = new FileInputStream( consumerProguardFile );
          mergedConsumerProguardFileBuilder.append(
            IOUtils.toString( consumerProguardFileInputStream ) );
          mergedConsumerProguardFileBuilder.append( SystemUtils.LINE_SEPARATOR );
          IOUtils.closeQuietly( consumerProguardFileInputStream );
    try
      mergedConsumerProguardFileOutputStream = new FileOutputStream( mergedConsumerProguardFile );
      IOUtils.write( mergedConsumerProguardFileBuilder, mergedConsumerProguardFileOutputStream );
origin: jamesagnew/hapi-fhir

Collection<File> files = FileUtils.listFiles(targetDirectory, new String[] { "xml", "json" }, true);
for (File nextFile : files) {
  ourLog.debug("Checking file: {}", nextFile);
    inputString = IOUtils.toString(new FileInputStream(nextFile), "UTF-8");
  } catch (IOException e) {
    throw new MojoFailureException("Failed to read file: " + nextFile, e);
    ourLog.info("Trimming contents of resource: {} - From {} to {}", nextFile, FileUtils.byteCountToDisplaySize(inputString.length()), FileUtils.byteCountToDisplaySize(outputString.length()));
    myByteCount += (inputString.length() - outputString.length());
    myFileCount++;
    try {
      String f = nextFile.getAbsolutePath();
      Writer w = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8");
      w = new BufferedWriter(w);
      w.append(outputString);
origin: commons-io/commons-io

    new BufferedOutputStream(new FileOutputStream(testFile1));
try {
  TestUtils.generateTestData(output1, 1234);
} finally {
  IOUtils.closeQuietly(output1);
    new BufferedOutputStream(new FileOutputStream(testFile2));
try {
  TestUtils.generateTestData(output, 4321);
} finally {
  IOUtils.closeQuietly(output);
subDir.mkdir();
final File subFile = new File(subDir, "A.txt");
FileUtils.writeStringToFile(subFile, "HELLO WORLD", "UTF8");
final File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase");
FileUtils.deleteDirectory(destDir);
destDir.mkdirs();
FileUtils.copyDirectory(srcDir, destDir);
final long srcSize = FileUtils.sizeOfDirectory(srcDir);
assertTrue("Size > 0", srcSize > 0);
assertEquals(srcSize, FileUtils.sizeOfDirectory(destDir));
assertTrue(new File(destDir, "sub/A.txt").exists());
origin: commons-io/commons-io

@Test
public void testMoveDirectory_Rename() throws Exception {
  final File dir = getTestDirectory();
  final File src = new File(dir, "testMoveDirectory1Source");
  final File testDir = new File(src, "foo");
  final File testFile = new File(testDir, "bar");
  testDir.mkdirs();
  if (!testFile.getParentFile().exists()) {
    throw new IOException("Cannot create file " + testFile
        + " as the parent directory does not exist");
  }
  final BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(testFile));
  try {
    TestUtils.generateTestData(output, 0);
  } finally {
    IOUtils.closeQuietly(output);
  }
  final File destination = new File(dir, "testMoveDirectory1Dest");
  FileUtils.deleteDirectory(destination);
  // Move the directory
  FileUtils.moveDirectory(src, destination);
  // Check results
  assertTrue("Check Exist", destination.exists());
  assertTrue("Original deleted", !src.exists());
  final File movedDir = new File(destination, testDir.getName());
  final File movedFile = new File(movedDir, testFile.getName());
  assertTrue("Check dir moved", movedDir.exists());
  assertTrue("Check file moved", movedFile.exists());
}
origin: webanno/webanno

@Override
public void createTemplate(Project aProject, File aContent, String aFileName, String aUsername)
  throws IOException
{
  String templatePath = dir.getAbsolutePath() + "/" + PROJECT_FOLDER + "/" + aProject.getId()
      + MIRA + MIRA_TEMPLATE;
  FileUtils.forceMkdir(new File(templatePath));
  copyLarge(new FileInputStream(aContent), new FileOutputStream(new File(templatePath
      + aFileName)));
  Logging.setMDC(aProject.getId(), aUsername);
  log.info("Removed template file [{}] from project [{}] ({})", aFileName, aProject.getName(),
      aProject.getId());
  Logging.clearMDC();
}
origin: commons-io/commons-io

@Test
public void testDeleteQuietlyFile() throws IOException {
  final File testFile = new File(getTestDirectory(), "testDeleteQuietlyFile");
  if (!testFile.getParentFile().exists()) {
    throw new IOException("Cannot create file " + testFile
        + " as the parent directory does not exist");
  }
  final BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(testFile));
  try {
    TestUtils.generateTestData(output, 0);
  } finally {
    IOUtils.closeQuietly(output);
  }
  assertTrue(testFile.exists());
  FileUtils.deleteQuietly(testFile);
  assertFalse("Check No Exist", testFile.exists());
}
origin: azkaban/azkaban

 logger.info("Uploading file " + name);
 final File archiveFile = new File(tempDir, name);
 out = new BufferedOutputStream(new FileOutputStream(archiveFile));
 IOUtils.copy(item.getInputStream(), out);
 out.close();
} finally {
 if (out != null) {
  out.close();
  FileUtils.deleteDirectory(tempDir);
origin: hyperledger/fabric-sdk-java

Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, true);
  fileInputStream = new FileInputStream(childFile);
  archiveOutputStream.putArchiveEntry(archiveEntry);
    IOUtils.copy(fileInputStream, archiveOutputStream);
  } finally {
    IOUtils.closeQuietly(fileInputStream);
    archiveOutputStream.closeArchiveEntry();
  childrenFiles = org.apache.commons.io.FileUtils.listFiles(chaincodeMetaInf, null, true);
    final String relativePath = Paths.get("META-INF", metabase.relativize(childFile.toURI()).getPath()).toString();
    fileInputStream = new FileInputStream(childFile);
    archiveOutputStream.putArchiveEntry(archiveEntry);
      IOUtils.copy(fileInputStream, archiveOutputStream);
    } finally {
      IOUtils.closeQuietly(fileInputStream);
origin: com.github.geoladris.plugins/layers-editor

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {
 Config config = (Config) getServletContext().getAttribute(Geoladris.ATTR_CONFIG);
 File backupDir = new File(config.getDir(), BACKUP_FOLDER);
 File layersJSON = new File(config.getDir(), LAYERS_JSON);
 if (layersJSON.exists()) {
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss_");
  File layersJSONBack = new File(backupDir, format.format(new Date()).concat(LAYERS_JSON));
  FileUtils.copyFile(layersJSON, layersJSONBack);
  layersJSON.delete();
  layersJSON.createNewFile();
  BufferedReader reader = req.getReader();
  OutputStream out = new FileOutputStream(layersJSON);
  IOUtils.copy(reader, new BufferedOutputStream(out), UTF_8);
  out.close();
  reader.close();
  logger.info("All OK, layers.json updated: 200");
  resp.setStatus(HttpServletResponse.SC_OK);
 } else {
  logger.error("No layers.json file found in PORTAL_CONFIG_DIR");
  resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
    "No layers.json file found in PORTAL_CONFIG_DIR");
 }
}
origin: mpetazzoni/ttorrent

try {
 if (Boolean.TRUE.equals(createFlag)) {
  fos = new FileOutputStream(filenameValue);
   List<File> files = new ArrayList<File>(FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE));
   Collections.sort(files);
   torrent = TorrentCreator.create(source, files, announceList.get(0).get(0), announceList, creator, pieceLengthVal);
  fos.write(new TorrentSerializer().serialize(torrent));
 } else {
  new TorrentParser().parseFromFile(new File(filenameValue));
} finally {
 if (fos != System.out) {
  IOUtils.closeQuietly(fos);
org.apache.commons.ioFileUtils

Javadoc

General file manipulation utilities.

Facilities are provided in the following areas:

  • writing to a file
  • reading from a file
  • make a directory including parent directories
  • copying files and directories
  • deleting files and directories
  • converting to and from a URL
  • listing files and directories by filter and extension
  • comparing file content
  • file last changed date
  • calculating a checksum

Origin of code: Excalibur, Alexandria, Commons-Utils

Most used methods

  • deleteDirectory
    Deletes a directory recursively.
  • readFileToString
    Reads the contents of a file into a String. The file is always closed.
  • writeStringToFile
    Writes a String to a file creating the file if it does not exist using the default encoding for the
  • deleteQuietly
    Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directori
  • copyFile
    Copy bytes from a File to an OutputStream. This method buffers the input internally, so there is no
  • listFiles
    Finds files within a given directory (and optionally its subdirectories) which match an array of ext
  • forceMkdir
    Makes a directory, including any necessary but nonexistent parent directories. If there already exis
  • copyDirectory
    Copies a whole directory to a new location. This method copies the contents of the specified source
  • forceDelete
    Deletes a file. If file is a directory, delete it and all sub-directories. The difference between Fi
  • write
    Writes a CharSequence to a file creating the file if it does not exist using the default encoding fo
  • copyInputStreamToFile
    Copies bytes from an InputStream source to a filedestination. The directories up to destination will
  • readLines
    Reads the contents of a file line by line to a List of Strings. The file is always closed.
  • copyInputStreamToFile,
  • readLines,
  • readFileToByteArray,
  • writeByteArrayToFile,
  • copyURLToFile,
  • moveFile,
  • cleanDirectory,
  • openInputStream,
  • openOutputStream,
  • copyFileToDirectory

Popular in Java

  • Running tasks concurrently on multiple threads
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • getSupportFragmentManager (FragmentActivity)
  • runOnUiThread (Activity)
  • Kernel (java.awt.image)
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • Format (java.text)
    The base class for all formats. This is an abstract base class which specifies the protocol for clas
  • MessageFormat (java.text)
    Produces concatenated messages in language-neutral way. New code should probably use java.util.Forma
  • ArrayList (java.util)
    ArrayList is an implementation of List, backed by an array. All optional operations including adding
  • Dictionary (java.util)
    Note: Do not use this class since it is obsolete. Please use the Map interface for new implementatio
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now