List of usage examples for java.io File getAbsoluteFile
public File getAbsoluteFile()
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 w w w. j a va 2s .co 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:com.csipsimple.utils.PreferencesWrapper.java
private static File getSubFolder(String subFolder) { File root = getStorageFolder(); if (root != null) { File dir = new File(root.getAbsoluteFile() + File.separator + subFolder); dir.mkdirs();//from w w w.ja va 2 s . com return dir; } return null; }
From source file:com.hmiard.blackwater.projects.Builder.java
/** * Building a new project.//from w w w . j a va2s . c o m * * @param projectName String * @param serverNames ArrayList * @param location String */ public static void buildNewProject(String projectName, ArrayList<String> serverNames, String location, ConsoleEmulator consoleListener) { try { consoleListener.clean(); consoleListener.push("Project creation started...\n\n"); projectName = projectName.substring(0, 1).toUpperCase() + projectName.substring(1); String projectUrl = location + "\\" + projectName; buildFolder(projectUrl); buildFolder(projectUrl + "\\bin"); buildFolder(projectUrl + "\\src"); buildFolder(projectUrl + "\\.blackwater"); ArrayList<String> realServerNames = new ArrayList<>(); for (String name : serverNames) realServerNames.add(name.replace("!", "")); // Creating the configuration Properties configuration = new Properties(); File tokens = new File(projectUrl + "\\.blackwater\\tokens.properties"); configuration.setProperty("PATH", projectUrl); configuration.setProperty("NAME", projectName); configuration.setProperty("SERVERS", Parser.parseArrayToStringList(",", realServerNames)); configuration.setProperty("LAST_UPDATE", new Date().toString()); configuration.store(new FileOutputStream(tokens), "Blackwater build version : " + Start.VERSION); consoleListener.push("Tokens generated.\n"); // Creating composer.json... JSONObject composerJSON = new JSONObject(); JSONObject autoload = new JSONObject(); JSONObject psr0 = new JSONObject(); JSONObject require = new JSONObject(); autoload.put("psr-0", psr0); composerJSON.put("autoload", autoload); composerJSON.put("require", require); require.put("blackwater/blackwaterp", Start.blackwaterpVersion); File composer = new File(projectUrl + "\\composer.json"); if (!composer.createNewFile()) { consoleListener.push("\nWeird composer stuff happened... Aborting.\n"); return; } BufferedWriter cw = new BufferedWriter(new FileWriter(composer.getAbsoluteFile())); String content = composerJSON.toString(4).replaceAll("\\\\", ""); cw.write(content); cw.close(); consoleListener.push("File created : composer.json\n"); // Creating the servers... consoleListener.push("Server creation started...\n"); for (String name : serverNames) if (name.charAt(0) == '!') appendServer(projectUrl, name.replace("!", ""), consoleListener, false); else appendServer(projectUrl, name, consoleListener, true); // Copying composer.phar consoleListener.push("Installing local composer wrapper...\n"); copyFile(new File("resources/packages/composer.phar"), new File(composer.getParent() + "\\bin\\composer.phar")); // Building... consoleListener.push("Building dependencies...\n"); new Thread(new ChildProcess("php bin/composer.phar install", composer.getParentFile(), consoleListener, () -> { NewProjectAppScreenPresenter presenter = (NewProjectAppScreenPresenter) consoleListener.app; presenter.projectCreatedCallback(projectUrl, consoleListener); })).start(); } catch (JSONException | IOException e) { e.printStackTrace(); } }
From source file:com.sangupta.jerry.util.FileUtils.java
/** * List the files in the given path string with wild cards. * //from w w w . j av a 2s. com * @param baseDir * the base directory to search for files in * * @param filePathWithWildCards * the file path to search in - can be absolute * * @param recursive * whether to look in sub-directories or not * * @param additionalFilters * additional file filters that need to be used when scanning for * files * * @return the list of files and directories that match the criteria */ public static List<File> listFiles(File baseDir, String filePathWithWildCards, boolean recursive, List<IOFileFilter> additionalFilters) { if (filePathWithWildCards == null) { throw new IllegalArgumentException("Filepath cannot be null"); } // change *.* to * filePathWithWildCards = filePathWithWildCards.replace("*.*", "*"); // normalize filePathWithWildCards = FilenameUtils.normalize(filePathWithWildCards); if (filePathWithWildCards.endsWith(File.pathSeparator)) { filePathWithWildCards += "*"; } // check if this is an absolute path or not String prefix = FilenameUtils.getPrefix(filePathWithWildCards); final boolean isAbsolute = !prefix.isEmpty(); // change the base dir if absolute directory if (isAbsolute) { baseDir = new File(filePathWithWildCards); if (!baseDir.isDirectory()) { // not a directory - get the base directory filePathWithWildCards = baseDir.getName(); if (filePathWithWildCards.equals("~")) { filePathWithWildCards = "*"; } if (AssertUtils.isEmpty(filePathWithWildCards)) { filePathWithWildCards = "*"; } baseDir = baseDir.getParentFile(); if (baseDir == null) { baseDir = getUsersHomeDirectory(); } } } // check if the provided argument is a directory File dir = new File(filePathWithWildCards); if (dir.isDirectory()) { baseDir = dir.getAbsoluteFile(); filePathWithWildCards = "*"; } else { // let's check for base directory File parent = dir.getParentFile(); if (parent != null) { baseDir = parent.getAbsoluteFile(); filePathWithWildCards = dir.getName(); } } // check for user home String basePath = baseDir.getPath(); if (basePath.startsWith("~")) { basePath = getUsersHomeDirectory().getAbsolutePath() + File.separator + basePath.substring(1); basePath = FilenameUtils.normalize(basePath); baseDir = new File(basePath); } // now read the files WildcardFileFilter wildcardFileFilter = new WildcardFileFilter(filePathWithWildCards, IOCase.SYSTEM); IOFileFilter finalFilter = wildcardFileFilter; if (AssertUtils.isNotEmpty(additionalFilters)) { additionalFilters.add(0, wildcardFileFilter); finalFilter = new AndFileFilter(additionalFilters); } Collection<File> files = org.apache.commons.io.FileUtils.listFiles(baseDir, finalFilter, recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE); return (List<File>) files; }
From source file:dk.statsbiblioteket.util.Files.java
/** * Copies a file (not a folder).//from w w w . j a va 2s .c o m * * @param source the file to copy. * @param destination where to copy the file to. If this is an existing * directory, {@code source} will be copied into it, * otherwise {@code source} will copied to this file. * @param overwrite whether or not to overwrite if the destination * already exists. * @throws IOException thrown if there was an error writing to the * destination file, or if the input file doidn't exist * or if the source was a directory. * @throws FileNotFoundException thrown if the source file did not exist. * @throws FileAlreadyExistsException if there's already a file at * {@code destination} and {@code overwrite} was * {@code false}. */ private static void copyFile(File source, File destination, boolean overwrite) throws IOException { log.trace("copyFile(" + source + ", " + destination + ", " + overwrite + ") called"); source = source.getAbsoluteFile(); destination = destination.getAbsoluteFile(); if (!source.exists()) { throw new FileNotFoundException("The source '" + source + "' does not exist"); } if (destination.isDirectory()) { throw new IOException("The destination '" + destination + "' is a directory"); } if (destination.exists() && destination.isDirectory()) { destination = new File(destination, source.getName()); } if (!overwrite && destination.exists()) { throw new FileAlreadyExistsException(destination.toString()); } // BufferedInputStream is not used, as it chokes > 2GB InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); try { byte[] buf = new byte[2028]; int count = 0; while ((count = in.read(buf)) != -1) { out.write(buf, 0, count); } } finally { in.close(); out.close(); } destination.setExecutable(source.canExecute()); }
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//from w ww . ja v a2 s .com * @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:net.rptools.lib.FileUtil.java
public static void unzip(ZipInputStream in, File destDir) throws IOException { if (in == null) throw new IOException("input stream cannot be null"); // Prepare destination destDir.mkdirs();/*w w w . ja v a2 s . c o m*/ File absDestDir = destDir.getAbsoluteFile(); // Pull out the files OutputStream out = null; ZipEntry entry = null; try { while ((entry = in.getNextEntry()) != null) { if (entry.isDirectory()) continue; // Prepare file destination File entryFile = new File(absDestDir, entry.getName()); entryFile.getParentFile().mkdirs(); out = new FileOutputStream(entryFile); IOUtils.copy(in, out); IOUtils.closeQuietly(out); in.closeEntry(); } } finally { IOUtils.closeQuietly(out); } }
From source file:eu.skqs.bertie.standalone.BertieStandalone.java
public static void processWithFile() throws Exception { logger.log(Level.INFO, "Processing started."); JCas jcas = null;// w ww. ja va2s . com CAS cas = null; TypePriorities typePriorities = null; // Generate jcas object try { typePriorities = TypePrioritiesFactory.createTypePriorities(); } catch (ResourceInitializationException e) { e.printStackTrace(); } try { cas = CasCreationUtils.createCas(createTypeSystemDescription(), typePriorities, null); jcas = cas.getJCas(); } catch (Exception e) { e.printStackTrace(); logger.log(Level.WARNING, "CAS object could not be generated."); } // Read the document File currentFile = new File(filePath); FileInputStream inputStream = new FileInputStream(currentFile); SourceDocumentInformation annotation = new SourceDocumentInformation(jcas); annotation.setUri(currentFile.getAbsoluteFile().toString()); annotation.addToIndexes(); logger.log(Level.INFO, currentFile.getAbsoluteFile().toString()); try { TeiDeserializer.deserialize(inputStream, cas); } catch (SAXException e) { e.printStackTrace(); throw new Exception(e); } finally { inputStream.close(); } AnalysisEngineDescription engine0 = AnalysisEngineFactory .createEngineDescription(AuxiliaryAnalysisEngine.class); // Shared resource bindResource(engine0, AuxiliaryAnalysisEngine.MODEL_KEY, SPARQLSharedResource.class, owlPath); AnalysisEngineDescription engine1 = AnalysisEngineFactory .createEngineDescription(InterpunctionAnalysisEngine.class); AnalysisEngineDescription engine2 = AnalysisEngineFactory .createEngineDescription(NumberUnitAnalysisEngine.class); AnalysisEngineDescription engine3 = AnalysisEngineFactory .createEngineDescription(PersNameAnalysisEngine.class); // Shared resource bindResource(engine3, PersNameAnalysisEngine.MODEL_KEY, PersNameResource.class, owlPath); AnalysisEngineDescription engine4 = AnalysisEngineFactory .createEngineDescription(DateTimeAnalysisEngine.class); // Shared resource bindResource(engine4, DateTimeAnalysisEngine.MODEL_KEY, SPARQLSharedResource.class, owlPath); AnalysisEngineDescription engine5 = AnalysisEngineFactory .createEngineDescription(PlaceNameAnalysisEngine.class); // Shared resource bindResource(engine5, PlaceNameAnalysisEngine.MODEL_KEY, PlaceNameResource.class, owlPath); SimplePipeline.runPipeline(jcas, engine0, engine1, engine2, engine3, engine4, engine5); // Deduplication AnalysisEngineDescription deduplicator = AnalysisEngineFactory .createEngineDescription(DeduplicatorAnalysisEngine.class); // TEI serializer AnalysisEngineDescription writer = AnalysisEngineFactory.createEngineDescription(TeiAnalysisEngine.class); SimplePipeline.runPipeline(jcas, engine0, engine1, engine2, engine3, engine4, engine5, deduplicator, writer); }
From source file:com.aurel.track.admin.server.dbbackup.DatabaseBackupBL.java
private static void restoreDatabase(File zipFile, String driver, String url, String user, String password, String attachemntDir) throws DatabaseBackupBLException { LOGGER.debug("Restore database: zipFile:" + zipFile.getAbsoluteFile() + " url=" + url); String restoreDir = HandleHome.getTrackplus_Home() + File.separator + HandleHome.DATA_DIR + File.separator + DB_RESTORE_TMP_DIR;/*from w ww.jav a2s .c o m*/ File fdir = new File(restoreDir); FileUtil.deltree(fdir); fdir.mkdirs(); try { FileUtil.unzipFile(zipFile, fdir); } catch (IOException e) { LOGGER.error("Error on unzip backup file:\"" + zipFile.getAbsolutePath() + "\" in directory: " + fdir.getAbsolutePath()); DatabaseBackupBLException ex = new DatabaseBackupBLException("Error on unzip backup file:\"" + zipFile.getAbsolutePath() + "\" in directory:" + fdir.getAbsolutePath(), e); ex.setLocalizedKey("admin.server.databaseBackup.err.cantUnZipFile"); ex.setLocalizedParams(new Object[] { zipFile.getAbsolutePath() }); throw ex; } String databaseName = MetaDataBL.getDatabaseType(url); LOGGER.debug("databaseName=" + databaseName); String fileSchema = restoreDir + File.separator + databaseName + "_schema.sql"; String fileSchemaConstraints = restoreDir + File.separator + databaseName + "_schema_constraints.sql"; DatabaseInfo databaseInfo = new DatabaseInfo(driver, url, user, password); try { boolean emptyDB = MetaDataBL.checkEmptyDatabase(databaseInfo); if (!emptyDB) { LOGGER.error("Target database is not empty!"); throw new DatabaseBackupBLException("Target database is not empty!"); } } catch (DDLException e) { e.printStackTrace(); throw new DatabaseBackupBLException("Can't create schema DB:" + e.getMessage(), e); } LOGGER.info("Importing schema DB..."); try { DataWriter.executeScript(fileSchema, databaseInfo); LOGGER.info("Importing schema DB successfuly!"); } catch (DDLException e) { e.printStackTrace(); throw new DatabaseBackupBLException("Can't create schema DB:" + e.getMessage(), e); } LOGGER.info("Importing data..."); try { DataWriter.writeDataToDB(databaseInfo, restoreDir); LOGGER.info("Importing data successfuly!"); } catch (DDLException e) { e.printStackTrace(); throw new DatabaseBackupBLException("Can't import data:" + e.getMessage(), e); } LOGGER.info("Importing constraints..."); try { DataWriter.executeScript(fileSchemaConstraints, databaseInfo); LOGGER.info("Importing constraints successfuly!"); } catch (DDLException e) { e.printStackTrace(); throw new DatabaseBackupBLException("Can't import constraints:" + e.getMessage(), e); } if (attachemntDir != null) { LOGGER.info("Importing attachments..."); File attachmentDirDist = new File(attachemntDir + File.separator + HandleHome.DATA_DIR + File.separator + AttachBL.AttachmentsName); if (!attachmentDirDist.exists()) { attachmentDirDist.mkdirs(); } String attach = restoreDir + File.separator + ATTACHMENTS_NAME; File fAttach = new File(attach); if (fAttach.exists()) { FileUtil.copyDirectory(fAttach, attachmentDirDist); } LOGGER.info("Done importing attachments!"); } }
From source file:com.drunkendev.io.recurse.tests.RecursionTest.java
/** * Given a {@link File} object, test if it is likely to be a symbolic link. * * @param file/* w w w. j ava 2s . com*/ * File to test for symbolic link. * @return {@code true} if {@code file} is a symbolic link. * @throws NullPointerException * If {@code file} is null. * @throws IOException * If a symbolic link could not be determined. This is ultimately * caused by a call to {@link File#getCanonicalFile()}. */ private static boolean isSymbolicLink(File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); } File canon; if (file.getParent() == null) { canon = file; } else { File canonDir = file.getParentFile().getCanonicalFile(); canon = new File(canonDir, file.getName()); } return !canon.getCanonicalFile().equals(canon.getAbsoluteFile()); }