Java Code Examples for org.apache.commons.io.FileUtils#moveFileToDirectory()

The following examples show how to use org.apache.commons.io.FileUtils#moveFileToDirectory() . 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: DeleteFileOnDiskStep.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Override
protected Void doExecute() throws InvalidProcessStateException {
	File file = context.consumeFile();
	
	if (file.exists()) {
		logger.debug("Deleting file '{}' on disk.", file.getAbsolutePath());

		try {
			FileUtils.moveFileToDirectory(file, H2HConstants.TRASH_DIRECTORY, true);
			setRequiresRollback(true);
		} catch (IOException e) {
			logger.warn("File '{}' could not be moved to the trash directory and gets deleted.",
					file.getAbsolutePath());
			FileUtils.deleteQuietly(file);
		}
	} else {
		logger.warn("File '{}' cannot be deleted as it does not exist.", file.getAbsolutePath());
	}
	
	return null;
}
 
Example 2
Source File: FileSystemHelper.java    From ModPackDownloader with MIT License 6 votes vote down vote up
static void moveFromLocalRepo(final DownloadableFile downloadableFile, final String fileName, boolean downloadToLocalRepo, String modFolder) {
	val newProjectName = getProjectNameOrDefault(downloadableFile.getName());
	String folder = downloadableFile.getFolder();
	if (Strings.isNullOrEmpty(folder)) {
		folder = modFolder;
	}
	try {
		File downloadedFile = getDownloadedFile(fileName, folder);
		if (downloadToLocalRepo) {
			FileUtils.copyFileToDirectory(getLocalFile(fileName, newProjectName), new File(folder));
		} else if (!downloadedFile.exists()) {
			FileUtils.moveFileToDirectory(getLocalFile(fileName, newProjectName), new File(folder), true);
		}
		if (!Strings.isNullOrEmpty(downloadableFile.getRename())) {
			downloadedFile.renameTo(new File(downloadedFile.getParent() + File.separator + downloadableFile.getRename()));
		}
	} catch (final IOException e) {
		log.error("Could not copy {} from local repo.", newProjectName, e);
	}
}
 
Example 3
Source File: DeleteFileOnDiskStep.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Override
protected Void doRollback() throws InvalidProcessStateException {
	File file = context.consumeFile();
	File trashFile = new File(H2HConstants.TRASH_DIRECTORY, file.getName());

	if (trashFile.exists()) {
		try {
			FileUtils.moveFileToDirectory(trashFile, file.getParentFile(), true);
			setRequiresRollback(false);
		} catch (IOException e) {
			logger.warn("File '{}' could not be moved to the original folder.",
					trashFile.getAbsolutePath());
		}
	} else {
		logger.warn("File '{}' cannot be recovered from trash as it does not exist.",
				trashFile.getAbsolutePath());
	}
	
	return null;
}
 
Example 4
Source File: ColumnarSegmentStore.java    From kylin with Apache License 2.0 5 votes vote down vote up
private void commitFragmentsMerge(FragmentsMergeResult mergeResult) throws IOException {
    mergeWriteLock.lock();
    try {
        mergeResult.getOrigFragments();
        removeFragments(mergeResult.getOrigFragments());
        DataSegmentFragment fragment = new DataSegmentFragment(baseStorePath, cubeName, segmentName,
                mergeResult.getMergedFragmentId());
        FileUtils.moveFileToDirectory(mergeResult.getMergedFragmentDataFile(), fragment.getFragmentFolder(), true);
        FileUtils.moveFileToDirectory(mergeResult.getMergedFragmentMetaFile(), fragment.getFragmentFolder(), true);
        fragments.add(fragment);
    } finally {
        mergeWriteLock.unlock();
    }
}
 
Example 5
Source File: TestFile.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void moveToDirectory(File target) {
    if (target.exists() && !target.isDirectory()) {
            throw new RuntimeException(String.format("Target '%s' is not a directory", target));
    }
    try {
        FileUtils.moveFileToDirectory(this, target, true);
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not move test file '%s' to directory '%s'", this, target), e);
    }
}
 
Example 6
Source File: ModelArchive.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
private static void moveToTopLevel(File from, File to) throws IOException {
    File[] list = from.listFiles();
    if (list != null) {
        for (File file : list) {
            if (file.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(file, to, false);
            } else {
                FileUtils.moveFileToDirectory(file, to, false);
            }
        }
    }
}
 
Example 7
Source File: Updater.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
private void moveUpdatedFiles(File updateFiles) throws IOException {
    File[] files = updateFiles.listFiles();
    if (files == null) throw new IllegalStateException("Cannot read update files.");

    for (File file : files) {
        File destFile = new File(currentFiles, file.getName());
        if (destFile.exists()) FileUtils.forceDelete(destFile);

        if (file.isDirectory()) FileUtils.moveDirectoryToDirectory(file, currentFiles, true);
        else FileUtils.moveFileToDirectory(file, currentFiles, true);
    }
}
 
Example 8
Source File: DataDrivenImportJob.java    From aliyun-maxcompute-data-collectors with Apache License 2.0 5 votes vote down vote up
private void writeAvroSchema(final Schema schema) throws IOException {
  // Generate schema in JAR output directory.
  final File schemaFile = new File(options.getJarOutputDir(), schema.getName() + ".avsc");

  LOG.info("Writing Avro schema file: " + schemaFile);
  FileUtils.forceMkdir(schemaFile.getParentFile());
  FileUtils.writeStringToFile(schemaFile, schema.toString(true));

  // Copy schema to code output directory.
  try {
    FileUtils.moveFileToDirectory(schemaFile, new File(options.getCodeOutputDir()), true);
  } catch (final IOException e) {
    LOG.debug("Could not move Avro schema file to code output directory.", e);
  }
}
 
Example 9
Source File: PFileIO.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@PhonkMethod(description = "Move a file to a directory", example = "")
@PhonkMethodParam(params = {"name", "destination"})
public void move(String name, String to) {
    File fromFile = new File(getAppRunner().getProject().getFullPathForFile(name));
    File dir = new File(getAppRunner().getProject().getFullPathForFile(to));

    dir.mkdirs();
    try {
        FileUtils.moveFileToDirectory(fromFile, dir, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: ColumnarSegmentStore.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void commitFragmentsMerge(FragmentsMergeResult mergeResult) throws IOException {
    mergeWriteLock.lock();
    try {
        mergeResult.getOrigFragments();
        removeFragments(mergeResult.getOrigFragments());
        DataSegmentFragment fragment = new DataSegmentFragment(baseStorePath, cubeName, segmentName,
                mergeResult.getMergedFragmentId());
        FileUtils.moveFileToDirectory(mergeResult.getMergedFragmentDataFile(), fragment.getFragmentFolder(), true);
        FileUtils.moveFileToDirectory(mergeResult.getMergedFragmentMetaFile(), fragment.getFragmentFolder(), true);
        fragments.add(fragment);
    } finally {
        mergeWriteLock.unlock();
    }
}
 
Example 11
Source File: FileSystemDataStore.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Moves product download zip into the given destination.
 * <p><b>Note:</b> generates the zip of product if necessary.</p>
 *
 * @param product     product to move.
 * @param destination destination of product
 */
private void moveProduct (Product product, String destination)
{

   if (destination == null || destination.trim ().isEmpty ())
   {
      return;
   }

   Path zip_destination = Paths.get (destination);
   String download_path = product.getDownloadablePath ();
   try
   {
      if (download_path != null)
      {
         File product_zip_file = Paths.get (download_path).toFile ();
         FileUtils.moveFileToDirectory (
               product_zip_file, zip_destination.toFile (), true);
      }
      else
      {
         Path product_path = Paths.get (product.getPath ().getPath ());
         if (UnZip.supported (product_path.toAbsolutePath ().toString ()))
         {
            FileUtils.moveFileToDirectory (
                  product_path.toFile (), zip_destination.toFile (), true);
         }
         else
         {
            zip_destination.resolve (product_path.getFileName ());
            generateZip (product_path.toFile (), zip_destination.toFile ());
         }
      }
   }
   catch (IOException e)
   {
      LOGGER.error("Cannot move product: " + product.getPath () +
            " into " + destination, e);
   }
}
 
Example 12
Source File: TestFile.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void moveToDirectory(File target) {
    if (target.exists() && !target.isDirectory()) {
            throw new RuntimeException(String.format("Target '%s' is not a directory", target));
    }
    try {
        FileUtils.moveFileToDirectory(this, target, true);
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not move test file '%s' to directory '%s'", this, target), e);
    }
}
 
Example 13
Source File: AvroFileToPojoModuleTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private void writeAvroFile(File outputFile)
{
  DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(new Schema.Parser().parse(AVRO_SCHEMA));
  try (DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
    dataFileWriter.create(new Schema.Parser().parse(AVRO_SCHEMA), outputFile);

    for (GenericRecord record : recordList) {
      dataFileWriter.append(record);
    }
    FileUtils.moveFileToDirectory(new File(outputFile.getAbsolutePath()), new File(testMeta.dir), true);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 14
Source File: DefaultGoPluginActivatorIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldNotLoadClassesFoundInMETA_INFEvenIfTheyAreProperGoExtensionPoints() throws Exception {
    File bundleWithActivator = createBundleWithActivator(BUNDLE_DIR_WHICH_HAS_PROPER_ACTIVATOR, DummyTestPlugin.class);
    File sourceClassFile = new File(bundleWithActivator, "com/thoughtworks/go/plugin/activation/test/DummyTestPlugin.class");
    File destinationFile = new File(bundleWithActivator, "META-INF/com/thoughtworks/go/plugin/activation/test/");
    FileUtils.moveFileToDirectory(sourceClassFile, destinationFile, true);

    installBundleFoundInDirectory(bundleWithActivator);

    GoPluginDescriptor descriptor = registry.getPlugin(GO_TEST_DUMMY_SYMBOLIC_NAME);
    assertThat(descriptor.isInvalid()).isTrue();
    assertThat(descriptor.getStatus().getMessages()).containsExactly(NO_EXT_ERR_MSG);
}
 
Example 15
Source File: ImportJobServiceActivator.java    From website with GNU Affero General Public License v3.0 4 votes vote down vote up
public void stageFile(File file) throws IOException {
    String filename = FilenameUtils.getName(file.getPath());
    FileUtils.moveFileToDirectory(file, new File(stagingFolder), true);
    importJobService.createImportJob(FilenameUtils.concat(stagingFolder, filename));
    return;
}
 
Example 16
Source File: CustomProcessorUploadHandler.java    From streamline with Apache License 2.0 4 votes vote down vote up
private void moveFileToDirectory (File fileToMove, File moveToDirectory) throws IOException {
    FileUtils.moveFileToDirectory(fileToMove, moveToDirectory, false);
}
 
Example 17
Source File: AvroFileInputOperatorTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
private void writeAvroFile(File outputFile) throws IOException
{

  DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(
      new Schema.Parser().parse(AVRO_SCHEMA));

  DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
  dataFileWriter.create(new Schema.Parser().parse(AVRO_SCHEMA), outputFile);

  for (GenericRecord record : recordList) {
    dataFileWriter.append(record);
  }

  dataFileWriter.close();

  FileUtils.moveFileToDirectory(new File(outputFile.getAbsolutePath()), new File(testMeta.dir), true);

}
 
Example 18
Source File: LogProvider.java    From restcommander with Apache License 2.0 4 votes vote down vote up
/**
 * 20130924: add for all none standard folder and folder of adhoc components
 * 
 * @param dateForArchive
 * @param logFolder
 */
public static void moveFilesForAppLogs(String dateForArchive,
		String logFolder) {

	try {
		String appLogsFolderPath = logFolder;
		List<String> fileNamesForAppLogs = FileIoUtils
				.getFileNamesInFolder(appLogsFolderPath);

		String destDirPath = generateAppLogAchiveFolderDate(dateForArchive,
				logFolder);

		// now create folder
		FileIoUtils.createFolder(destDirPath);

		File destDir = new File(destDirPath);

		for (String appLogFileName : fileNamesForAppLogs) {

			// only move for that date.
			if (!appLogFileName.startsWith(dateForArchive)
			// 201309 for none standard logs and for ADHOCDATASTORE
			// components
					&& !(appLogFileName.startsWith(VarUtils.ADHOCDATASTORE) && appLogFileName
							.contains(dateForArchive))

			) {
				continue;
			}

			String appLogAbsolutePath = generateAppLogAbsolutePath(logFolder);
			String appLogFileFullPath = appLogAbsolutePath + appLogFileName;

			File srcFile = new File(appLogFileFullPath);
			FileUtils.moveFileToDirectory(srcFile, destDir, true);

		}// end for loop

	} catch (Throwable e) {
		e.printStackTrace();
		models.utils.LogUtils.printLogError("Error in moveFilesForAppLogs "
				+ DateUtils.getNowDateTimeStrSdsm());
	}

}
 
Example 19
Source File: NativeFolderWatchServiceTest.java    From PeerWasp with MIT License 4 votes vote down vote up
@Test
public void testManySimultaneousEvents() throws Exception {
	watchService.start(basePath);

	List<File> folderList = new ArrayList<File>();
	List<File> fileList = new ArrayList<File>();

	int numberOfFolders = WatchServiceTestHelpers.randomInt(5, 50);
	int numberOfFiles = WatchServiceTestHelpers.randomInt(200, 1000);

	// create random folders & save files(paths) in list
	String folderName = null;

	for (int i = 1; i <= numberOfFolders; i++){

		folderName = WatchServiceTestHelpers.getRandomString(15, "abcdefghijklmnopqrstuvwxyz123456789");
		String subDirString = "\\" + folderName  +"\\";
		File subDir = Paths.get(basePath.toString(), subDirString).toFile();
		FileUtils.forceMkdir(subDir);

		folderList.add(subDir);
	}

	// create random files in base path & save files(paths) in list
	File randomFile;

	for (int i = 1; i <= numberOfFiles; i++){

		String randomFileName = WatchServiceTestHelpers.getRandomString(15, "abcdefghijklmnopqrstuvwxyz123456789");

		randomFile = Paths.get(basePath.toString(), randomFileName + ".txt").toFile();
		FileWriter out = new FileWriter(randomFile);
		WatchServiceTestHelpers.writeRandomData(out, NUM_CHARS_SMALL_FILE);
		out.close();

		fileList.add(randomFile);
	}

	// pick a random number of files and move them randomly to folders
	int randomNumberOfMovements = WatchServiceTestHelpers.randomInt(1, numberOfFiles);

	for (int i = 1; i <= randomNumberOfMovements; i++){

		// randomly pick a file from the fileList
		int randomFilePick = WatchServiceTestHelpers.randomInt(0, fileList.size()-1);
		File randomFileToMove = fileList.get(randomFilePick);

		// randomly pick a target sub directory
		int randomFolderPick = WatchServiceTestHelpers.randomInt(0, folderList.size()-1);
		File randomTargetFolder = folderList.get(randomFolderPick);

		FileUtils.moveFileToDirectory(randomFileToMove, randomTargetFolder, false);

		// remove moved file from file list
		fileList.remove(randomFileToMove);
	}

	sleep();

//	Mockito.verify(fileManager, Mockito.times(randomNumberOfMovements)).move(Matchers.anyObject(), Matchers.anyObject());
}
 
Example 20
Source File: CommonUtils.java    From torrssen2 with MIT License 4 votes vote down vote up
public static List<String> removeDirectory(String path, String outer, SettingRepository settingRepository) {
    String[] exts = {};
    Optional<Setting> exceptExtSetting = settingRepository.findByKey("EXCEPT_EXT");
    if(exceptExtSetting.isPresent()) {
        exts = StringUtils.split(StringUtils.lowerCase(exceptExtSetting.get().getValue()), ",");
    }

    Optional<Setting> delDirSetting = settingRepository.findByKey("DEL_DIR");
    
    if (delDirSetting.isPresent()) {
        if(Boolean.parseBoolean(delDirSetting.get().getValue())) {
            File file = new File(path, outer);
            if (file.isDirectory()) {
                Collection<File> subFiles;
                if(exts != null) {
                    NotFileFilter fileFilter = new NotFileFilter(new SuffixFileFilter(exts)); 
                    subFiles = FileUtils.listFiles(new File(path, outer), fileFilter, TrueFileFilter.INSTANCE);
                } else {
                    subFiles = FileUtils.listFiles(new File(path, outer), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
                }
                
                List<String> ret = new ArrayList<>();

                try {
                    for(File subFile: subFiles) {
                        log.debug(subFile.getPath() + ":" + subFile.getName());
                        File remove = new File(path, subFile.getName());
                        if (remove.isFile()) {
                            FileUtils.forceDelete(remove);
                        }
                        FileUtils.moveFileToDirectory(subFile, new File(path), true);
                        ret.add(subFile.getName());
                    }
                    FileUtils.forceDelete(new File(path, outer));
                } catch (IOException e) {
                    log.error(e.getMessage());
                }

                return ret;
            } 
        }
    }

    return null;
}