private File findTempFile(String s) { String os = System.getProperty("os.name").toLowerCase(); File f; if (os.indexOf("linux") >= 0) { // DEBUG System.out.println("LINUX"); f = new File("/tmp/Cryptography/"); if (!f.exists()) f.mkdirs(); f = new File(f.toPath() + "/" + s); if (f.exists()) if (!f.delete()) System.err.println("No writing access to temp files"); } else if (os.indexOf("win") >= 0) { // DEBUG System.out.println("WINDOWS"); f = new File( "C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Local\\Temp\\Cryptography\\"); if (!f.exists()) f.mkdirs(); f = new File(f.toPath() + "\\" + s); if (f.exists()) if (!f.delete()) System.err.println("No writing access to temp files"); } else { System.err.println("Unbekanntes Betriebssystem!"); return null; } return f; }
public void cp(String source, String destination, boolean recursive) throws NoSuchFileException, IOException { File srcFile = getPath(source).toFile(); File destFile = getPath(destination).toFile(); if (!srcFile.exists()) { throw new FileNotFoundException(source); } if (srcFile.isDirectory() && !recursive) { String exMsg = "'%s' is Directory"; throw new IOException(String.format(exMsg, source)); } if (srcFile.equals(destFile)) { String exMsg = "'%s' and '%s' are the same"; throw new IOException(String.format(exMsg, source, destination)); } if (srcFile.isFile()) { if (destFile.isDirectory()) { destFile = new File(destFile, source); } Files.copy(srcFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { Files.walkFileTree(srcFile.toPath(), new FileVisitorImpl(srcFile, destFile)); } }
/** * Uploads the dsl file of a user to an auxiliar folder, if it's not upload returns an error * * @param file * @param idUser */ @RequestMapping(method = RequestMethod.POST, value = "/uploadDSL") public ResponseEntity<String> handleFileUploadDSL( @RequestParam("dsl") MultipartFile file, @RequestParam("idUser") String idUser) { // target DSL name String name = "dsl.yml"; if (!file.isEmpty()) { try { // User folder File userFolder = new File(idUser); if (!userFolder.exists()) Files.createDirectory(userFolder.toPath()); // Auxiliar folder where the temporal configuration files are // copy String folderAux = idUser + "/aux"; File folder = new File(folderAux); if (!folder.exists()) Files.createDirectory(folder.toPath()); // Copy DSL file BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(folderAux + "/" + name))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); log.info("DSL copied: " + idUser); } catch (Exception e) { log.warn("DSL not copied:" + e.getMessage()); throw new InternalError("Error copying: " + e.getMessage()); } } else { log.warn("DSL not copied, empty file: " + idUser); throw new BadRequestError("Empty file"); } return new ResponseEntity<>("copied", HttpStatus.OK); }
private int cpRecursive(String[] args, String directory, Status status) throws IOException { if (args.length < 2) { return 1; } File source = new File(directory + File.separator + args[2]); if (!source.exists()) { return 1; } File destination = new File(args[3] + File.separator + args[2]); if (destination.exists()) { String[] rmArgs = {"rm", "-r", destination.getName()}; new RmCommand().execute(rmArgs, status); } if (!source.isDirectory()) { Files.copy(source.toPath(), destination.toPath()); return 0; } Files.copy(source.toPath(), destination.toPath()); File[] listFiles = source.listFiles(); if (listFiles.length == 0) { return 0; } for (File f : listFiles) { String[] newArgs = {"cp", "-r", f.getName(), destination.getAbsolutePath()}; cpRecursive(newArgs, source.getAbsolutePath(), status); } return 0; }
public void testMultipleListeners() throws Exception { File rootDirectory = Files.createTempDir(); File subDirectory = createDirectoryIn("subdir", rootDirectory); ResourceAccumulator resourceAccumulator1 = new ResourceAccumulator(rootDirectory.toPath(), createInclusivePathPrefixSet()); ResourceAccumulator resourceAccumulator2 = new ResourceAccumulator(rootDirectory.toPath(), createInclusivePathPrefixSet()); assertTrue(getResources(resourceAccumulator1).isEmpty()); assertTrue(getResources(resourceAccumulator2).isEmpty()); createFileIn("New.java", subDirectory); waitForFileEvents(); List<AbstractResource> resources1 = getResources(resourceAccumulator1); assertEquals(1, resources1.size()); assertTrue(resources1.get(0).getPath().endsWith("New.java")); List<AbstractResource> resources2 = getResources(resourceAccumulator2); assertEquals(1, resources2.size()); assertTrue(resources2.get(0).getPath().endsWith("New.java")); resourceAccumulator1.shutdown(); resourceAccumulator2.shutdown(); }
public void testSymlinks() throws Exception { File scratchDirectory = Files.createTempDir(); File newFile = createFileIn("New.java", scratchDirectory); File rootDirectory = Files.createTempDir(); File subDirectory = Files.createTempDir(); ResourceAccumulator resourceAccumulator = new ResourceAccumulator(rootDirectory.toPath(), createInclusivePathPrefixSet()); assertTrue(getResources(resourceAccumulator).isEmpty()); // Symlink in a subdirectory and then symlink in a contained file. java.nio.file.Files.createSymbolicLink( new File(rootDirectory, "sublink").toPath(), subDirectory.toPath()) .toFile(); java.nio.file.Files.createSymbolicLink( new File(subDirectory, "New.java").toPath(), newFile.toPath()) .toFile(); waitForFileEvents(); List<AbstractResource> resources = getResources(resourceAccumulator); assertEquals(1, resources.size()); assertTrue(resources.get(0).getPath().endsWith("sublink/New.java")); resourceAccumulator.shutdown(); }
@Test public void should_create_given_directory() throws Exception { visitor.preVisitDirectory(source.toPath().resolve("widgets"), null); assertThat(exists(destination.toPath().resolve("widgets"))).isTrue(); }
private synchronized File unpackFromFileURL(URL url, String fileName, ClassLoader cl) { File resource; try { resource = new File(URLDecoder.decode(url.getPath(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new VertxException(e); } boolean isDirectory = resource.isDirectory(); File cacheFile = new File(cacheDir, fileName); if (!isDirectory) { cacheFile.getParentFile().mkdirs(); try { if (ENABLE_CACHING) { Files.copy(resource.toPath(), cacheFile.toPath()); } else { Files.copy(resource.toPath(), cacheFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } catch (FileAlreadyExistsException ignore) { } catch (IOException e) { throw new VertxException(e); } } else { cacheFile.mkdirs(); String[] listing = resource.list(); for (String file : listing) { String subResource = fileName + "/" + file; URL url2 = cl.getResource(subResource); unpackFromFileURL(url2, subResource, cl); } } return cacheFile; }
public void drop() throws Exception { for (int i = 0; i < 16; i++) { File subDir = new File(mainDir, String.valueOf(i) + ".dir"); for (int j = 0; j < 16; j++) { if (databases[i][j] != null) { File dbFile = new File(subDir, String.valueOf(j) + ".dat"); if (dbFile.exists()) { try { Files.delete(dbFile.toPath()); } catch (SecurityException | IOException e) { throw new Exception("Access violation: cannon delete database file"); } } } } if (subDir.exists()) { try { Files.delete(subDir.toPath()); } catch (DirectoryNotEmptyException e) { throw new Exception("Cannot remove table subdirectory. Redundant files"); } catch (SecurityException | IOException e) { throw new Exception("Access violation: cannot delete database subdirectory"); } } } try { Files.delete(mainDir.toPath()); } catch (DirectoryNotEmptyException e) { throw new Exception("Cannot remove main table directory. Redundant files"); } catch (SecurityException | IOException e) { throw new Exception("Access violation: cannot delete main database directory"); } }
@Test public void testTerminateQueueCannotDeleteDirectory() throws IOException { String queueName = "queueCannotDelete"; File queueDir = new File("target", queueName); ReportExporter exporter = mock(ReportExporter.class); BatchProcessorConfig config = mock(BatchProcessorConfig.class); when(config.getDataDirectory()).thenReturn("target"); when(config.getQueueSize()).thenReturn(5); FileUtil.deleteDirectory(queueDir); queueFactory = new QueueFactory(config, exporter); Set<PosixFilePermission> permissions = new HashSet<>(); permissions.add(PosixFilePermission.OWNER_READ); queueFactory.create(queueName); assertTrue(queueDir.exists()); Files.setPosixFilePermissions(queueDir.toPath(), permissions); try { queueFactory.terminate(queueName); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { assertTrue(true); } permissions = new HashSet<>(); permissions.add(PosixFilePermission.OWNER_WRITE); permissions.add(PosixFilePermission.OWNER_READ); permissions.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(queueDir.toPath(), permissions); FileUtil.deleteDirectory(queueDir); }
/** * @param srcFilename * @param dstFilename */ public static void copyOrDie(String srcFilename, String dstFilename) { File src = new File(srcFilename); File dst = new File(dstFilename); System.out.printf("Copy or die: %s, %s\n", srcFilename, dstFilename); if (!src.exists()) { return; } // Ensure target file is non-existent. deleteOrDie(dstFilename); // Copy file. try { if (src.isDirectory()) { org.apache.commons.io.FileUtils.copyDirectory(src, dst); } else { Files.copy(src.toPath(), dst.toPath()); } } catch (IOException ex) { throw new FatalError( "copyOrDie failed for '" + srcFilename + "' -> '" + dstFilename + "'", ex); } // Check if target exists. existsOrDie(dst); }
/** Generate evolutions. */ @Override public void create() { if (!environment.isProd()) { config .serverConfigs() .forEach( (key, serverConfig) -> { String evolutionScript = generateEvolutionScript(servers.get(key)); if (evolutionScript != null) { File evolutions = environment.getFile("conf/evolutions/" + key + "/1.sql"); try { String content = ""; if (evolutions.exists()) { content = new String(Files.readAllBytes(evolutions.toPath()), "utf-8"); } if (content.isEmpty() || content.startsWith("# --- Created by Ebean DDL")) { environment.getFile("conf/evolutions/" + key).mkdirs(); if (!content.equals(evolutionScript)) { Files.write(evolutions.toPath(), evolutionScript.getBytes("utf-8")); } } } catch (IOException e) { throw new RuntimeException(e); } } }); } }
static void setupCleanDirectories(File jbossHomeDir, Properties props) { File tempRoot = getTempRoot(props); if (tempRoot == null) { return; } File originalConfigDir = getFileUnderAsRoot( jbossHomeDir, props, ServerEnvironment.SERVER_CONFIG_DIR, "configuration", true); File originalDataDir = getFileUnderAsRoot(jbossHomeDir, props, ServerEnvironment.SERVER_DATA_DIR, "data", false); try { File configDir = new File(tempRoot, "config"); Files.createDirectory(configDir.toPath()); File dataDir = new File(tempRoot, "data"); Files.createDirectory(dataDir.toPath()); // For jboss.server.deployment.scanner.default File deploymentsDir = new File(tempRoot, "deployments"); Files.createDirectory(deploymentsDir.toPath()); copyDirectory(originalConfigDir, configDir); if (originalDataDir.exists()) { copyDirectory(originalDataDir, dataDir); } props.put(ServerEnvironment.SERVER_BASE_DIR, tempRoot.getAbsolutePath()); props.put(ServerEnvironment.SERVER_CONFIG_DIR, configDir.getAbsolutePath()); props.put(ServerEnvironment.SERVER_DATA_DIR, dataDir.getAbsolutePath()); } catch (IOException e) { throw EmbeddedLogger.ROOT_LOGGER.cannotSetupEmbeddedServer(e); } }
public void testSymlinkInfiniteLoop() throws Exception { File rootDirectory = Files.createTempDir(); File subDirectory = Files.createTempDir(); ResourceAccumulator resourceAccumulator = new ResourceAccumulator(rootDirectory.toPath(), createInclusivePathPrefixSet()); assertTrue(getResources(resourceAccumulator).isEmpty()); // Symlink in a loop java.nio.file.Files.createSymbolicLink( new File(rootDirectory, "sublink").toPath(), subDirectory.toPath()) .toFile(); java.nio.file.Files.createSymbolicLink( new File(subDirectory, "sublink").toPath(), rootDirectory.toPath()) .toFile(); createFileIn("New.java", subDirectory); waitForFileEvents(); try { // Should throw an error if resourceAccumulator got stuck in an infinite directory scan loop. getResources(resourceAccumulator); fail(); } catch (FileSystemException expected) { // Expected } resourceAccumulator.shutdown(); }
public String call() throws IOException, IllegalArgumentException { if (urlToFetch == null) { throw new IllegalArgumentException("Need a URL to fetch"); } log.info("urlToFetch: " + urlToFetch); String[] filenameParts = urlToFetch.split("/"); String basename = filenameParts[filenameParts.length - 1]; String absoluteFilePath = outputDir + File.separator + basename; File finalMP3 = new File(absoluteFilePath); Path pathFinalMP3 = finalMP3.toPath(); if (finalMP3.exists()) { log.info("Looks like " + basename + " is already there.. Skipping"); } else { GenericUrl url = new GenericUrl(urlToFetch); HttpRequest request = requestFactory.buildGetRequest(url); File f = downloadToTempFile(request); Path pathTempMP3 = f.toPath(); moveToFile(pathTempMP3, pathFinalMP3); } return pathFinalMP3.toString(); }
@Override public <T> T run(Callable<T> r) { T result = null; try { synchronized (store) { result = r.call(); File temp = new File(store.getParentFile(), "temp_" + store.getName()); FileOutputStream file = new FileOutputStream(temp); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(properties); out.writeObject(maps); out.flush(); out.close(); file.flush(); file.close(); Files.move( temp.toPath(), store.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { // If something happened here, that is a serious bug so we need to assert. throw Assert.failure("Failure flushing FlatFileKeyValueStorage", e); } return result; }
private static void copyFiles(String str) throws IOException { File destFile = new File( "/home/vinay/work/finovera/web/static/src/main/webapp/resources/images/logos/" + str); File[] fiportFiles = readFilesName("fiport/webapps", str); File[] finoveraFiles = readFilesName("finovera/web", str); boolean found = false; for (File fp : fiportFiles) { found = false; for (File fn : finoveraFiles) { if (fp.getName().trim().equalsIgnoreCase(fn.getName().trim())) { found = true; } } if (found == false) { Path sourcePath = fp.toPath(); Path destPath = destFile.toPath(); Files.copy(sourcePath, destPath.resolve(sourcePath.getFileName())); System.out.println(fp.getName() + ": Image copied to Finovera."); } } }
/** * @param templateDir The directory that contains the template version of the project. * @param temporaryFolder The directory where the clone of the template directory should be * written. By requiring a {@link TemporaryFolder} rather than a {@link File}, we can ensure * that JUnit will clean up the test correctly. */ public ProjectWorkspace(File templateDir, DebuggableTemporaryFolder temporaryFolder) { Preconditions.checkNotNull(templateDir); Preconditions.checkNotNull(temporaryFolder); this.templatePath = templateDir.toPath(); this.destDir = temporaryFolder.getRoot(); this.destPath = destDir.toPath(); }
/** Create a jar file from the classes directory, creating it directly in the toolkit. */ private static String createJarFile(File toolkitLib, final File classesDir) throws IOException { final Path classesPath = classesDir.toPath(); Path jarPath = Files.createTempFile(toolkitLib.toPath(), "classes", ".jar"); try (final JarOutputStream jarOut = new JarOutputStream( new BufferedOutputStream(new FileOutputStream(jarPath.toFile()), 128 * 1024))) { Files.walkFileTree( classesDir.toPath(), new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { File classFile = file.toFile(); if (classFile.isFile()) { // Write the entry followed by the data. Path relativePath = classesPath.relativize(file); JarEntry je = new JarEntry(relativePath.toString()); je.setTime(classFile.lastModified()); jarOut.putNextEntry(je); final byte[] data = new byte[32 * 1024]; try (final BufferedInputStream classIn = new BufferedInputStream(new FileInputStream(classFile), data.length)) { for (; ; ) { int count = classIn.read(data); if (count == -1) break; jarOut.write(data, 0, count); } } jarOut.closeEntry(); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { dir.toFile().delete(); return FileVisitResult.CONTINUE; } }); } return jarPath.getFileName().toString(); }
public static void reconstructTurtle(File partFolder, File reconstructed) throws IOException { Path tmpOut = Files.createTempFile(partFolder.toPath(), "reconstr", ".tmp"); FileOutputStream dstOut = new FileOutputStream(tmpOut.toFile()); FileChannel dstOutChannel = dstOut.getChannel(); try { if (!Files.isDirectory(partFolder.toPath())) throw new IOException("Not a directory: " + partFolder); File[] fileList = FileUtils.listFiles(partFolder, new PrefixFileFilter("part"), TrueFileFilter.TRUE) .toArray(new File[0]); Arrays.sort(fileList); RandomAccessFile inputFile; inputFile = new RandomAccessFile(fileList[0], "r"); inputFile.getChannel().transferTo(0, inputFile.length(), dstOutChannel); inputFile.close(); for (int i = 1; i < fileList.length; i++) { inputFile = new RandomAccessFile(fileList[i], "r"); long lastPrefix = findTurtlePrefixEnd(inputFile); inputFile .getChannel() .transferTo(lastPrefix, inputFile.length() - lastPrefix, dstOutChannel); inputFile.close(); } } finally { dstOut.close(); } Files.move( tmpOut, reconstructed.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileUtils.deleteQuietly(tmpOut.toFile()); FileUtils.deleteQuietly(partFolder); }
/* Function Name: decryptSplitFileHandler // Description: Handles the decryption of split files // Calling Function: decryptFileHandler // Parameters: File parent - file to be decrypted // String indent - indentation for log file */ private void decryptSplitFileHandler(File parent, String indent) { try { log.write(indent.concat(parent.getName()).concat("\n")); String dePath = fileOne.getAbsolutePath(); String deName = fileOne.getName().substring(2, (fileOne.getName().length() - 1)); dePath = dePath.substring(0, (dePath.length() - fileOne.getName().length())); dePath = dePath.concat(deName); StatusGuiBuilder.updateStatusGui(fname); crypto.doSplitDecrypt(fileOne, fileTwo, new File(dePath)); decryptSplitFileHandlerHelper(dePath); Files.delete(fileOne.toPath()); Files.delete(fileTwo.toPath()); } catch (IOException ex) { Logger.getLogger(DirectoryStructureDecryptionHandler.class.getName()) .log(Level.SEVERE, null, ex); } }
static void copyFile(File src, File dst) throws IOException { Path parent = dst.toPath().getParent(); if (parent != null) { Files.createDirectories(parent); } Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING); }
@Test public void testResourceBase() throws Exception { testdir.ensureEmpty(); File resBase = testdir.getFile("docroot"); FS.ensureDirExists(resBase); File foobar = new File(resBase, "foobar.txt"); File link = new File(resBase, "link.txt"); createFile(foobar, "Foo Bar"); String resBasePath = resBase.getAbsolutePath(); ServletHolder defholder = context.addServlet(DefaultServlet.class, "/"); defholder.setInitParameter("resourceBase", resBasePath); defholder.setInitParameter("gzip", "false"); String response; response = connector.getResponses("GET /context/foobar.txt HTTP/1.0\r\n\r\n"); assertResponseContains("Foo Bar", response); if (!OS.IS_WINDOWS) { Files.createSymbolicLink(link.toPath(), foobar.toPath()); response = connector.getResponses("GET /context/link.txt HTTP/1.0\r\n\r\n"); assertResponseContains("404", response); context.addAliasCheck(new ContextHandler.ApproveAliases()); response = connector.getResponses("GET /context/link.txt HTTP/1.0\r\n\r\n"); assertResponseContains("Foo Bar", response); } }
private synchronized File unpackFromJarURL(URL url, String fileName, ClassLoader cl) { ZipFile zip = null; try { String path = url.getPath(); int idx1 = path.lastIndexOf(".jar!"); if (idx1 == -1) { idx1 = path.lastIndexOf(".zip!"); } int idx2 = path.lastIndexOf(".jar!", idx1 - 1); if (idx2 == -1) { idx2 = path.lastIndexOf(".zip!", idx1 - 1); } if (idx2 == -1) { File file = new File(URLDecoder.decode(path.substring(5, idx1 + 4), "UTF-8")); zip = new ZipFile(file); } else { String s = path.substring(idx2 + 6, idx1 + 4); File file = resolveFile(s); zip = new ZipFile(file); } String inJarPath = path.substring(idx1 + 6); String[] parts = JAR_URL_SEP_PATTERN.split(inJarPath); StringBuilder prefixBuilder = new StringBuilder(); for (int i = 0; i < parts.length - 1; i++) { prefixBuilder.append(parts[i]).append("/"); } String prefix = prefixBuilder.toString(); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (name.startsWith(prefix.isEmpty() ? fileName : prefix + fileName)) { File file = new File(cacheDir, prefix.isEmpty() ? name : name.substring(prefix.length())); if (name.endsWith("/")) { // Directory file.mkdirs(); } else { file.getParentFile().mkdirs(); try (InputStream is = zip.getInputStream(entry)) { if (ENABLE_CACHING) { Files.copy(is, file.toPath()); } else { Files.copy(is, file.toPath(), StandardCopyOption.REPLACE_EXISTING); } } catch (FileAlreadyExistsException ignore) { } } } } } catch (IOException e) { throw new VertxException(e); } finally { closeQuietly(zip); } return new File(cacheDir, fileName); }
public void replaceSnippets(File file, String encoding) throws IOException { final File temp = File.createTempFile("snippets", "txt"); replace(file, temp, encoding, false); if (!file.delete()) { throw new IOException("Could not delete file " + file); } Files.move(temp.toPath(), file.toPath()); }
private void writeIntoFile(int numOfDir, int numOfFile) { String dirString = String.valueOf(numOfDir) + ".dir"; String fileString = String.valueOf(numOfFile) + ".dat"; File dbDir = tableDir.toPath().resolve(dirString).normalize().toFile(); if (!dbDir.isDirectory()) { dbDir.mkdir(); } File dbFile = dbDir.toPath().resolve(fileString).normalize().toFile(); if (list[numOfDir][numOfFile].isEmpty()) { dbFile.delete(); if (dbDir.list().length == 0) { dbDir.delete(); } return; } RandomAccessFile db; try { db = new RandomAccessFile(dbFile, "rw"); try { db.setLength(0); Iterator<Map.Entry<String, String>> it; it = list[numOfDir][numOfFile].entrySet().iterator(); long[] pointers = new long[list[numOfDir][numOfFile].size()]; int counter = 0; while (it.hasNext()) { Map.Entry<String, String> m = (Map.Entry<String, String>) it.next(); String key = m.getKey(); db.write(key.getBytes("UTF-8")); db.write("\0".getBytes("UTF-8")); pointers[counter] = db.getFilePointer(); db.seek(pointers[counter] + 4); ++counter; } it = list[numOfDir][numOfFile].entrySet().iterator(); counter = 0; while (it.hasNext()) { Map.Entry<String, String> m = (Map.Entry<String, String>) it.next(); String value = m.getValue(); int curPointer = (int) db.getFilePointer(); db.seek(pointers[counter]); db.writeInt(curPointer); db.seek(curPointer); db.write(value.getBytes("UTF-8")); ++counter; } } catch (Exception e) { db.close(); throw new Exception(e); } db.close(); if (dbDir.list().length == 0) { dbDir.delete(); } } catch (Exception e) { throw new IllegalArgumentException(); } }
// This is a fail-safe wrapper around File.renameTo() since that can fail if the destination path // is on a // different file system or potentially for other causes which don't preclude other means of I/O. // renameTo() is the simplest and most efficient (and hopefully atomic) method, but we fall back // to the // more laborious byte-by-byte copy if it fails. public static void moveFile(java.io.File srcfile, java.io.File dstfile) throws java.io.IOException { if (srcfile.renameTo(dstfile)) { return; } java.nio.file.Path srcpath = srcfile.toPath(); copyFile(srcpath, dstfile.toPath()); deleteFile(srcpath); }
/** * Tries to move/rename a file from one path to another. Uses {@link java.nio.file.Files#move} * when available. Does not use {@link java.nio.file.StandardCopyOption#REPLACE_EXISTING} or any * other options. TODO candidate for moving to {@link Util} */ static void move(File src, File dest) throws IOException { try { Files.move(src.toPath(), dest.toPath()); } catch (IOException x) { throw x; } catch (Exception x) { throw new IOException(x); } }
@Test public void should_copy_given_file_from_source_directory() throws Exception { write(source.toPath().resolve("pbButton.json"), "contents".getBytes()); visitor.visitFile(source.toPath().resolve("pbButton.json"), null); assertThat(readAllBytes(destination.toPath().resolve("pbButton.json"))) .isEqualTo("contents".getBytes()); }
public void addJarDependency(String location) throws IllegalArgumentException { File f = new File(location); if (!f.exists()) { throw new IllegalArgumentException( "File not found. Invalid " + "third party dependency location:" + f.toPath().toAbsolutePath().toString()); } globalDependencies.add(f.toPath().toAbsolutePath()); }