List of usage examples for java.io File getCanonicalFile
public File getCanonicalFile() throws IOException
From source file:Main.java
public static boolean isSymlink(File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); }//from ww w .jav a 2s . c o m if (isSystemWindows()) { return false; } File fileInCanonicalDir = null; if (file.getParent() == null) { fileInCanonicalDir = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); fileInCanonicalDir = new File(canonicalDir, file.getName()); } return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile()); }
From source file:dk.netarkivet.common.utils.ZipUtils.java
/** Unzip a zipFile into a directory. This will create subdirectories * as needed./*from ww w. ja va 2 s .c om*/ * * @param zipFile The file to unzip * @param toDir The directory to create the files under. This directory * will be created if necessary. Files in it will be overwritten if the * filenames match. */ public static void unzip(File zipFile, File toDir) { ArgumentNotValid.checkNotNull(zipFile, "File zipFile"); ArgumentNotValid.checkNotNull(toDir, "File toDir"); ArgumentNotValid.checkTrue(toDir.getAbsoluteFile().getParentFile().canWrite(), "can't write to '" + toDir + "'"); ArgumentNotValid.checkTrue(zipFile.canRead(), "can't read '" + zipFile + "'"); InputStream inputStream = null; ZipFile unzipper = null; try { try { unzipper = new ZipFile(zipFile); Enumeration<? extends ZipEntry> entries = unzipper.entries(); while (entries.hasMoreElements()) { ZipEntry ze = entries.nextElement(); File target = new File(toDir, ze.getName()); // Ensure that its dir exists FileUtils.createDir(target.getCanonicalFile().getParentFile()); if (ze.isDirectory()) { target.mkdir(); } else { inputStream = unzipper.getInputStream(ze); FileUtils.writeStreamToFile(inputStream, target); inputStream.close(); } } } finally { if (unzipper != null) { unzipper.close(); } if (inputStream != null) { inputStream.close(); } } } catch (IOException e) { throw new IOFailure("Failed to unzip '" + zipFile + "'", e); } }
From source file:Main.java
/** A helper to make a URL from a filespec. */ private static URL makeURLFromFilespec(final String filespec, final String relativePrefix) throws IOException { // make sure the file is absolute & canonical file url File file = new File(decode(filespec)); // if we have a prefix and the file is not abs then prepend if (relativePrefix != null && !file.isAbsolute()) { file = new File(relativePrefix, filespec); }//from w w w . j av a2s . c o m // make sure it is canonical (no ../ and such) file = file.getCanonicalFile(); return file.toURI().toURL(); }
From source file:media_organizer.MediaInspector.java
private static boolean symbolicLink(File file) throws IOException { if (file == null) { throw new NullPointerException("NULL file object!"); }//from w w w .jav a 2s . c om File canonicalFile; if (file.getParent() == null) { canonicalFile = file; } else { File canonicalDir = file.getParentFile().getCanonicalFile(); canonicalFile = new File(canonicalDir, file.getName()); } return !canonicalFile.getCanonicalFile().equals(canonicalFile.getAbsoluteFile()); }
From source file:net.menthor.editor.v2.util.Util.java
public static File chooseFile(Component parent, String lastPath, String dialogTitle, String fileDescription, String fileExtension, boolean checkOverrideFile) throws IOException { JFileChooser fileChooser = createChooser(lastPath, checkOverrideFile); fileChooser.setDialogTitle(dialogTitle); FileNameExtensionFilter filter = new FileNameExtensionFilter(fileDescription, fileExtension); fileChooser.addChoosableFileFilter(filter); if (SystemUtil.onWindows()) fileChooser.setFileFilter(filter); fileChooser.setAcceptAllFileFilterUsed(false); if (fileChooser.showDialog(parent, "Ok") == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (!file.getName().endsWith("." + fileExtension)) { file = new File(file.getCanonicalFile() + "." + fileExtension); } else {/* ww w . j a v a 2 s . c o m*/ file = new File(file.getCanonicalFile() + ""); } return file; } else { return null; } }
From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java
private static File findSource(File sourcePath, Class<?> aClass) throws IOException { assert sourcePath != null; assert aClass != null; String[] segments = aClass.getName().split("\\."); //$NON-NLS-1$ File current = sourcePath;//from w w w . jav a 2 s .c o m for (int i = 0; i < segments.length - 1; i++) { current = new File(current, segments[i]); if (current.isDirectory() == false) { throw new FileNotFoundException(MessageFormat.format("{0} (for {1})", current, aClass.getName())); } } String name = segments[segments.length - 1]; int enclosing = name.indexOf('$'); if (enclosing >= 0) { name = name.substring(0, enclosing); } File file = new File(current, name + ".java"); //$NON-NLS-1$ if (file.isFile() == false) { if (current.isDirectory() == false) { throw new FileNotFoundException(MessageFormat.format("{0} (for {1})", file, aClass.getName())); } } return file.getCanonicalFile(); }
From source file:org.openflexo.toolbox.ZipUtils.java
public static final void unzip(File zip, File outputDir, IProgress progress) throws ZipException, IOException { Enumeration<? extends ZipEntry> entries; outputDir = outputDir.getCanonicalFile(); if (!outputDir.exists()) { boolean b = outputDir.mkdirs(); if (!b) { throw new IllegalArgumentException("Could not create dir " + outputDir.getAbsolutePath()); }/*w ww.ja v a2 s . c om*/ } if (!outputDir.isDirectory()) { throw new IllegalArgumentException( outputDir.getAbsolutePath() + "is not a directory or is not writeable!"); } ZipFile zipFile; zipFile = new ZipFile(zip); entries = zipFile.entries(); if (progress != null) { progress.resetSecondaryProgress(zipFile.size()); } while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (progress != null) { progress.setSecondaryProgress( FlexoLocalization.localizedForKey("unzipping") + " " + entry.getName()); } if (entry.getName().startsWith("__MACOSX")) { continue; } if (entry.isDirectory()) { // Assume directories are stored parents first then // children. // This is not robust, just for demonstration purposes. new File(outputDir, entry.getName().replace('\\', '/')).mkdirs(); continue; } File outputFile = new File(outputDir, entry.getName().replace('\\', '/')); if (outputFile.getName().startsWith("._")) { // This block is made to drop MacOS crap added to zip files if (zipFile.getEntry( entry.getName().substring(0, entry.getName().length() - outputFile.getName().length()) + outputFile.getName().substring(2)) != null) { continue; } if (new File(outputFile.getParentFile(), outputFile.getName().substring(2)).exists()) { continue; } } FileUtils.createNewFile(outputFile); InputStream zipStream = null; FileOutputStream fos = null; try { zipStream = zipFile.getInputStream(entry); if (zipStream == null) { System.err.println("Could not find input stream for entry: " + entry.getName()); continue; } fos = new FileOutputStream(outputFile); copyInputStream(zipStream, new BufferedOutputStream(fos)); } catch (IOException e) { e.printStackTrace(); System.err.println("Could not extract: " + outputFile.getAbsolutePath() + " maybe some files contains invalid characters."); } finally { IOUtils.closeQuietly(zipStream); IOUtils.closeQuietly(fos); } } Collection<File> listFiles = org.apache.commons.io.FileUtils.listFiles(outputDir, null, true); for (File file : listFiles) { if (file.isFile() && file.getName().startsWith("._")) { File f = new File(file.getParentFile(), file.getName().substring(2)); if (f.exists()) { file.delete(); } } } zipFile.close(); }
From source file:net.morimekta.idltool.IdlUtils.java
private static File getCacheDirectory(File cacheDir, String repository) throws IOException { if (!cacheDir.exists()) { if (!cacheDir.mkdirs()) { throw new IOException( "Unable to create cache directory " + cacheDir.getCanonicalFile().getAbsolutePath()); }/*from w w w . j av a2s . c o m*/ } String hash = Base64.getUrlEncoder() .encodeToString(DigestUtils.sha1(repository.getBytes(StandardCharsets.UTF_8))); return new File(cacheDir, hash).getCanonicalFile().getAbsoluteFile(); }
From source file:org.lilyproject.runtime.model.LilyRuntimeModelBuilder.java
private static void buildModules(List<ModuleDefinition> modules, Stack<String> wiringFileStack, Conf runtimeConf, ArtifactRepository repository, SourceLocations artifactSourceLocations) throws Exception { Conf modulesConf = runtimeConf.getRequiredChild("modules"); List<Conf> importConfs = modulesConf.getChildren(); for (Conf importConf : importConfs) { File fileToImport = null; ModuleSourceType sourceType = null; String version = "unknown"; String id = null;//ww w . java2 s . c om if (importConf.getName().equals("file")) { String path = PropertyResolver.resolveProperties(importConf.getAttribute("path")); File file = new File(path); if (file.getName().toLowerCase().endsWith(".xml")) { // Import a wiring.xml-type file includeWiring(file, modules, wiringFileStack, repository, artifactSourceLocations); } else { id = importConf.getAttribute("id"); fileToImport = new File(path); sourceType = ModuleSourceType.JAR; } } else if (importConf.getName().equals("artifact")) { id = importConf.getAttribute("id"); String groupId = importConf.getAttribute("groupId"); String artifactId = importConf.getAttribute("artifactId"); String classifier = importConf.getAttribute("classifier", null); // Version is optional for org.lilyproject artifacts version = groupId.equals("org.lilyproject") ? importConf.getAttribute("version", null) : importConf.getAttribute("version"); version = version == null ? LilyRuntime.getVersion() : version; File sourceLocation = artifactSourceLocations.getSourceLocation(groupId, artifactId); if (sourceLocation != null) { fileToImport = sourceLocation.getCanonicalFile(); if (!fileToImport.exists()) { throw new LilyRTException("Specified artifact source directory does not exist: " + fileToImport.getAbsolutePath(), importConf.getLocation()); } sourceType = ModuleSourceType.SOURCE_DIRECTORY; } else { fileToImport = repository.resolve(groupId, artifactId, classifier, version); sourceType = ModuleSourceType.JAR; } } else if (importConf.getName().equals("directory")) { id = importConf.getAttribute("id"); String dirName = PropertyResolver.resolveProperties(importConf.getAttribute("path")); // When basePath is specified, the directory specified in dirName will be resolved // against basePath. Moreover, basePath can contain a list of paths, // in which case each basePath will be combined with the path. (this is the only // reason for having basePath as a separate attribute) // (It would make sense to allow multiple values for path as well, but the // need hasn't come up) String basePath = importConf.getAttribute("basePath", null); if (basePath != null) { basePath = PropertyResolver.resolveProperties(basePath); String[] basePaths = basePath.split(File.pathSeparator); for (String path : basePaths) { path = path.trim(); if (path.length() > 0) { String subDirName = new File(new File(path), dirName).getAbsolutePath(); include(subDirName, id, modules, wiringFileStack, repository, artifactSourceLocations); } } } else { include(dirName, id, modules, wiringFileStack, repository, artifactSourceLocations); } } else { throw new LilyRTException("Unexpected node: " + importConf.getName(), importConf.getLocation()); } if (fileToImport != null) { if (!fileToImport.exists()) { throw new LilyRTException("Import does not exist: " + fileToImport.getAbsolutePath(), importConf.getLocation()); } ModuleDefinition moduleDefinition = new ModuleDefinition(id, fileToImport, sourceType); moduleDefinition.setLocation(importConf.getLocation()); moduleDefinition.setVersion(version); buildWiring(importConf, moduleDefinition); modules.add(moduleDefinition); } } }
From source file:com.cedarsoft.io.LinkUtils.java
/** * Deletes the symbolic link/*from w w w.j av a 2 s. c o m*/ * * @param linkFile the link file * @throws IOException if any. */ public static void deleteSymbolicLink(@Nonnull File linkFile) throws IOException { if (!linkFile.exists()) { throw new FileNotFoundException("No such symlink: " + linkFile); } // find the resource of the existing link: File canonicalFile = linkFile.getCanonicalFile(); // rename the resource, thus breaking the link: File temp = createTempFile("symlink", ".tmp", canonicalFile.getParentFile()); try { try { FileUtils.moveFile(canonicalFile, temp); } catch (IOException e) { throw new IOException("Couldn't rename resource when attempting to delete " + linkFile); } // delete the (now) broken link: if (!linkFile.delete()) { throw new IOException("Couldn't delete symlink: " + linkFile + " (was it a real file? is this not a UNIX system?)"); } } finally { // return the resource to its original name: try { FileUtils.moveFile(temp, canonicalFile); } catch (IOException e) { throw new IOException("Couldn't return resource " + temp + " to its original name: " + canonicalFile.getAbsolutePath() + "\n THE RESOURCE'S NAME ON DISK HAS " + "BEEN CHANGED BY THIS ERROR!\n"); } } }