List of usage examples for java.io File renameTo
public boolean renameTo(File dest)
From source file:com.plotsquared.iserver.util.FileUtils.java
/** * Add files to a zip file/*from ww w . j a v a 2s.com*/ * * @param zipFile Zip File * @param files Files to add to the zip * @param delete If the original files should be deleted * @throws Exception If anything goes wrong */ public static void addToZip(final File zipFile, final File[] files, final boolean delete) throws Exception { Assert.notNull(zipFile, files); if (!zipFile.exists()) { if (!zipFile.createNewFile()) { throw new RuntimeException("Couldn't create " + zipFile); } } final File temporary = File.createTempFile(zipFile.getName(), ""); //noinspection ResultOfMethodCallIgnored temporary.delete(); if (!zipFile.renameTo(temporary)) { throw new RuntimeException("Couldn't rename " + zipFile + " to " + temporary); } final byte[] buffer = new byte[1024 * 16]; // 16mb ZipInputStream zis = new ZipInputStream(new FileInputStream(temporary)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry e = zis.getNextEntry(); while (e != null) { String n = e.getName(); boolean no = true; for (File f : files) { if (f.getName().equals(n)) { no = false; break; } } if (no) { zos.putNextEntry(new ZipEntry(n)); int len; while ((len = zis.read(buffer)) > 0) { zos.write(buffer, 0, len); } } e = zis.getNextEntry(); } zis.close(); for (File file : files) { InputStream in = new FileInputStream(file); zos.putNextEntry(new ZipEntry(file.getName())); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } zos.closeEntry(); in.close(); } zos.close(); temporary.delete(); if (delete) { for (File f : files) { f.delete(); } } }
From source file:com.k_joseph.apps.multisearch.solr.AddCustomFieldsToSchema.java
/** * Overwrites the previous schema file with the newly generated * // ww w. ja v a 2 s.c o m * @param previousSchema currently used schema file * @param newSchema to be used instead of the previous */ private static void copyNewSchemaFileToPreviouslyUsed(String previousSchema, String newSchema) { File previousSchemaFile = new File(previousSchema); File newSchemaFile = new File(newSchema); if (previousSchemaFile.exists() && newSchemaFile.exists()) { String chartSearchBackUpPath = System.getProperty("user.home") + File.separator + ".multiSearch" + File.separator + "backup"; File chartSearchBackUp = new File(chartSearchBackUpPath); if (!chartSearchBackUp.exists()) { chartSearchBackUp.mkdir(); } previousSchemaFile.delete(); newSchemaFile.renameTo(previousSchemaFile); try { //Backing up the new schema file for easy retrieval after restarting or upgrading the module //TODO support an option clickat the UI where by the user can Reload the solrserver, //this would mean updating the schema file with back-up before the Reloading is done FileUtils.copyFileToDirectory(newSchemaFile, chartSearchBackUp); } catch (IOException e) { System.out.println("Error generated" + e); } } }
From source file:dk.netarkivet.common.utils.ZipUtils.java
/** GZip each of the files in fromDir, placing the result in toDir * (which will be created) with names having .gz appended. All non-file * (directory, link, etc) entries in the source directory will be * skipped with a quiet little log message. * * @param fromDir An existing directory/* w w w. j a v a 2s .c om*/ * @param toDir A directory where gzipped files will be placed. This * directory must not previously exist. * If the operation is not successful, the directory will not be created. */ public static void gzipFiles(File fromDir, File toDir) { ArgumentNotValid.checkNotNull(fromDir, "File fromDir"); ArgumentNotValid.checkNotNull(toDir, "File toDir"); ArgumentNotValid.checkTrue(fromDir.isDirectory(), "source '" + fromDir + "' must be an existing directory"); ArgumentNotValid.checkTrue(!toDir.exists(), "destination directory '" + toDir + "' must not exist"); File tmpDir = null; try { tmpDir = FileUtils.createUniqueTempDir(toDir.getAbsoluteFile().getParentFile(), toDir.getName()); File[] fromFiles = fromDir.listFiles(); for (File f : fromFiles) { if (f.isFile()) { gzipFileInto(f, tmpDir); } else { log.trace("Skipping non-file '" + f + "'"); } } if (!tmpDir.renameTo(toDir)) { throw new IOFailure("Failed to rename temp dir '" + tmpDir + "' to desired target '" + toDir + "'"); } } finally { if (tmpDir != null) { try { FileUtils.removeRecursively(tmpDir); } catch (IOFailure e) { log.debug("Error removing temporary" + " directory '" + tmpDir + "' after gzipping of '" + toDir + "'", e); } } } }
From source file:com.jimplush.goose.images.ImageSaver.java
/** * stores an image to disk and returns the path where the file was written * * @param imageSrc/*from www. j av a 2 s.co m*/ * @return */ public static String storeTempImage(HttpClient httpClient, String linkhash, String imageSrc, Configuration config) throws SecretGifException { String localSrcPath = null; HttpGet httpget = null; HttpResponse response = null; try { imageSrc = imageSrc.replace(" ", "%20"); if (logger.isDebugEnabled()) { logger.debug("Starting to download image: " + imageSrc); } HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, HtmlFetcher.emptyCookieStore); httpget = new HttpGet(imageSrc); response = httpClient.execute(httpget, localContext); String respStatus = response.getStatusLine().toString(); if (!respStatus.contains("200")) { return null; } HttpEntity entity = response.getEntity(); String fileExtension = ""; try { Header contentType = entity.getContentType(); } catch (Exception e) { logger.error(e.getMessage()); } // generate random token Random generator = new Random(); int randInt = generator.nextInt(); localSrcPath = config.getLocalStoragePath() + "/" + linkhash + "_" + randInt; if (logger.isDebugEnabled()) { logger.debug("Storing image locally: " + localSrcPath); } if (entity != null) { InputStream instream = entity.getContent(); OutputStream outstream = new FileOutputStream(localSrcPath); try { try { IOUtils.copy(instream, outstream); } catch (Exception e) { throw e; } finally { entity.consumeContent(); instream.close(); outstream.close(); } // get mime type and store the image extension based on that shiz fileExtension = ImageSaver.getFileExtension(config, localSrcPath); if (fileExtension == "" || fileExtension == null) { if (logger.isDebugEnabled()) { logger.debug("EMPTY FILE EXTENSION: " + localSrcPath); } return null; } File f = new File(localSrcPath); if (f.length() < config.getMinBytesForImages()) { if (logger.isDebugEnabled()) { logger.debug("TOO SMALL AN IMAGE: " + localSrcPath + " bytes: " + f.length()); } return null; } File newFile = new File(localSrcPath + fileExtension); f.renameTo(newFile); localSrcPath = localSrcPath + fileExtension; if (logger.isDebugEnabled()) { logger.debug("Image successfully Written to Disk"); } } catch (IOException e) { logger.error(e.toString(), e); } catch (SecretGifException e) { throw e; } catch (Exception e) { logger.error(e.getMessage()); } } } catch (IllegalArgumentException e) { logger.warn(e.getMessage()); } catch (SecretGifException e) { raise(e); } catch (ClientProtocolException e) { logger.error(e.toString()); } catch (IOException e) { logger.error(e.toString()); } catch (Exception e) { e.printStackTrace(); logger.error(e.toString()); e.printStackTrace(); } finally { httpget.abort(); } return localSrcPath; }
From source file:com.matze5800.paupdater.Functions.java
public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException { File tempFile = new File(Environment.getExternalStorageDirectory() + "/pa_updater", "temp_kernel.zip"); tempFile.delete();/*from w w w. j av a 2 s . c om*/ boolean renameOk = zipFile.renameTo(tempFile); if (!renameOk) { throw new RuntimeException( "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath()); } byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean notInFiles = true; for (File f : files) { if (f.getName().equals(name)) { notInFiles = false; break; } } if (notInFiles) { out.putNextEntry(new ZipEntry(name)); int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } } entry = zin.getNextEntry(); } zin.close(); for (int i = 0; i < files.length; i++) { InputStream in = new FileInputStream(files[i]); out.putNextEntry(new ZipEntry(files[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); tempFile.delete(); }
From source file:edu.stanford.muse.email.JarDocCache.java
/** returns a jar outputstream for the given filename. * copies over jar entries if the file was already existing. * unfortunately, we can't append to the end of a jar file easily. * see e.g.http://stackoverflow.com/questions/2223434/appending-files-to-a-zip-file-with-java * and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445 * may consider using truezip at some point, but the doc is dense. *///from www . j ava 2s. c o m private static JarOutputStream appendOrCreateJar(String filename) throws IOException { JarOutputStream jos; File f = new File(filename); if (!f.exists()) return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); // bak* is going to be all the previous file entries String bakFilename = filename + ".bak"; File bakFile = new File(bakFilename); f.renameTo(new File(bakFilename)); jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); JarFile bakJF; try { bakJF = new JarFile(bakFilename); } catch (Exception e) { log.warn("Bad jar file! " + bakFilename + " size " + new File(filename).length() + " bytes"); Util.print_exception(e, log); return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); } // copy all entries from bakJF to jos Enumeration<JarEntry> bakEntries = bakJF.entries(); while (bakEntries.hasMoreElements()) { JarEntry je = bakEntries.nextElement(); jos.putNextEntry(je); InputStream is = bakJF.getInputStream(je); // copy over everything from is to jos byte buf[] = new byte[32 * 1024]; // randomly 32K int nBytes; while ((nBytes = is.read(buf)) != -1) jos.write(buf, 0, nBytes); jos.closeEntry(); } bakFile.delete(); return jos; }
From source file:Main.java
public static boolean save(String fileName, Bitmap bitmap) { if (fileName == null || bitmap == null) { return false; }//from www . j a v a 2 s . c om boolean savedSuccessfully = false; OutputStream os = null; File imageFile = new File(fileName); File tmpFile = new File(imageFile.getAbsolutePath() + ".tmp"); try { if (!imageFile.getParentFile().exists()) { imageFile.getParentFile().mkdirs(); } os = new BufferedOutputStream(new FileOutputStream(tmpFile)); savedSuccessfully = bitmap.compress(Bitmap.CompressFormat.PNG, 100, os); } catch (Exception e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (savedSuccessfully && tmpFile != null && !tmpFile.renameTo(imageFile)) { savedSuccessfully = false; } if (!savedSuccessfully) { tmpFile.delete(); } } return savedSuccessfully; }
From source file:fi.mikuz.boarder.util.FileProcessor.java
public static void renameBoard(String originalBoardName, String newBoardName) { File oldLocation = new File(SoundboardMenu.mSbDir, originalBoardName); File newLocation = new File(SoundboardMenu.mSbDir, newBoardName); oldLocation.renameTo(newLocation); }
From source file:dk.netarkivet.common.utils.ZipUtils.java
/** Gunzip all .gz files in a given directory into another. Files in * fromDir not ending in .gz or not real files will be skipped with a * log entry./*from www .ja v a 2 s .c o m*/ * * @param fromDir The directory containing .gz files * @param toDir The directory to place the unzipped files in. This * directory must not exist beforehand. * @throws IOFailure if there are problems creating the output directory * or gunzipping the files. */ public static void gunzipFiles(File fromDir, File toDir) { ArgumentNotValid.checkNotNull(fromDir, "File fromDir"); ArgumentNotValid.checkNotNull(toDir, "File toDir"); ArgumentNotValid.checkTrue(fromDir.isDirectory(), "source directory '" + fromDir + "' must exist"); ArgumentNotValid.checkTrue(!toDir.exists(), "destination directory '" + toDir + "' must not exist"); File tempDir = FileUtils.createUniqueTempDir(toDir.getAbsoluteFile().getParentFile(), toDir.getName()); try { File[] gzippedFiles = fromDir.listFiles(); for (File f : gzippedFiles) { if (f.isFile() && f.getName().endsWith(GZIP_SUFFIX)) { gunzipInto(f, tempDir); } else { log.trace("Non-gzip file '" + f + "' found in gzip dir"); } } if (!tempDir.renameTo(toDir)) { throw new IOFailure( "Error renaming temporary directory '" + tempDir + "' to target directory '" + toDir); } } finally { FileUtils.removeRecursively(tempDir); } }
From source file:jenkins.model.RunIdMigrator.java
/** * 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} *///from w w w . j a v a2s.c om static void move(File src, File dest) throws IOException { Class<?> pathC; try { pathC = Class.forName("java.nio.file.Path"); } catch (ClassNotFoundException x) { // Java 6, do our best if (dest.exists()) { throw new IOException(dest + " already exists"); } if (src.renameTo(dest)) { return; } throw new IOException("could not move " + src + " to " + dest); } try { Method toPath = File.class.getMethod("toPath"); Class<?> copyOptionAC = Class.forName("[Ljava.nio.file.CopyOption;"); Class.forName("java.nio.file.Files").getMethod("move", pathC, pathC, copyOptionAC).invoke(null, toPath.invoke(src), toPath.invoke(dest), Array.newInstance(copyOptionAC.getComponentType(), 0)); } catch (InvocationTargetException x) { Throwable cause = x.getCause(); if (cause instanceof IOException) { throw (IOException) cause; } else { throw new IOException(cause); } } catch (Exception x) { throw new IOException(x); } }