List of usage examples for java.io File getCanonicalPath
public String getCanonicalPath() throws IOException
From source file:eu.annocultor.common.Utils.java
private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException { // This will hold a list of directories matching the pckgname. There may be // more than one if a package is split over multiple jars/paths Queue<File> directories = new LinkedList<File>(); try {/*from w w w .j a v a 2 s . c om*/ ClassLoader cld = Thread.currentThread().getContextClassLoader(); if (cld == null) { throw new ClassNotFoundException("Can't get class loader."); } String path = pckgname.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = cld.getResources(path); while (resources.hasMoreElements()) { directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8"))); } } catch (NullPointerException x) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Null pointer exception)"); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( pckgname + " does not appear to be a valid package (Unsupported encoding)"); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + pckgname); } Set<String> classes = new HashSet<String>(); // For every directory identified capture all the .class files while (!directories.isEmpty()) { File directory = directories.poll(); if (directory.exists()) { // Get the list of the files contained in the package File[] files = directory.listFiles(); for (File file : files) { // we are only interested in .class files if (file.getCanonicalPath().endsWith(".class")) { String fileName = file.getPath().substring(directory.getPath().length() + 1); pckgname = file.getPath() .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1); pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator)) .replaceAll("\\" + File.separator, "."); // if (!fileName.matches("(.+)\\$\\d\\.class")) // removes the .class extension classes.add(fileName.substring(0, fileName.length() - 6)); } // Add subdirs if (file.isDirectory()) { directories.add(file); } } } else { throw new ClassNotFoundException( pckgname + " (" + directory.getPath() + ") does not appear to be a valid package"); } } return classes; }
From source file:com.github.woz_dialog.ros_woz_dialog_project.TTSHTTPClient.java
public static void generateFile(byte[] data, File outputFile) { try {//www.jav a2 s . c o m AudioInputStream audioStream = getAudioStream(data); if (outputFile.getName().endsWith("wav")) { int nb = AudioSystem.write(audioStream, AudioFileFormat.Type.WAVE, new FileOutputStream(outputFile)); log.fine("WAV file written to " + outputFile.getCanonicalPath() + " (" + (nb / 1000) + " kB)"); } else { throw new RuntimeException("Unsupported encoding " + outputFile); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("could not generate file: " + e); } }
From source file:io.apigee.buildTools.enterprise4g.utils.ZipUtils.java
static void addDir(File dirObj, ZipOutputStream out, File root, String prefix) throws IOException { File[] files = dirObj.listFiles(); byte[] tmpBuf = new byte[1024]; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { addDir(files[i], out, root, prefix); continue; }// ww w . j a va2s.c om FileInputStream in = new FileInputStream(files[i].getAbsolutePath()); log.debug(" Adding: " + files[i].getAbsolutePath()); String relativePath = files[i].getCanonicalPath().substring(root.getCanonicalPath().length()); while (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } while (relativePath.startsWith("\\")) { relativePath = relativePath.substring(1); } String left = Matcher.quoteReplacement("\\"); String right = Matcher.quoteReplacement("/"); relativePath = relativePath.replaceAll(left, right); relativePath = (prefix == null) ? relativePath : prefix + "/" + relativePath; out.putNextEntry(new ZipEntry(relativePath)); int len; while ((len = in.read(tmpBuf)) > 0) { out.write(tmpBuf, 0, len); } out.closeEntry(); in.close(); } }
From source file:com.igormaznitsa.jcp.utils.PreprocessorUtils.java
@Nonnull public static String getFilePath(@Nullable final File file) { String result = ""; if (file != null) { try {/*from w w w .j av a 2 s . c o m*/ result = file.getCanonicalPath(); } catch (IOException ex) { result = file.getAbsolutePath(); } } return result; }
From source file:ffx.utilities.Keyword.java
/** * This method sets up configuration properties in the following precedence * * order:// w ww. j a va 2 s.com * * 1.) Structure specific properties (for example pdbname.properties) * * 2.) Java system properties a.) -Dkey=value from the Java command line b.) * System.setProperty("key","value") within Java code. * * 3.) User specific properties (~/.ffx/ffx.properties) * * 4.) System wide properties (file defined by environment variable * FFX_PROPERTIES) * * 5.) Internal force field definition. * * @since 1.0 * @param file a {@link java.io.File} object. * @return a {@link org.apache.commons.configuration.CompositeConfiguration} * object. */ public static CompositeConfiguration loadProperties(File file) { /** * Command line options take precedence. */ CompositeConfiguration properties = new CompositeConfiguration(); /** * Structure specific options are first. */ if (file != null) { String filename = file.getAbsolutePath(); filename = org.apache.commons.io.FilenameUtils.removeExtension(filename); String propertyFilename = filename + ".properties"; File structurePropFile = new File(propertyFilename); if (structurePropFile.exists() && structurePropFile.canRead()) { try { properties.addConfiguration(new PropertiesConfiguration(structurePropFile)); properties.addProperty("propertyFile", structurePropFile.getCanonicalPath()); } catch (ConfigurationException | IOException e) { logger.log(Level.INFO, " Error loading {0}.", filename); } } else { propertyFilename = filename + ".key"; structurePropFile = new File(propertyFilename); if (structurePropFile.exists() && structurePropFile.canRead()) { try { properties.addConfiguration(new PropertiesConfiguration(structurePropFile)); properties.addProperty("propertyFile", structurePropFile.getCanonicalPath()); } catch (ConfigurationException | IOException e) { logger.log(Level.INFO, " Error loading {0}.", filename); } } } } /** * Java system properties * * a.) -Dkey=value from the Java command line * * b.) System.setProperty("key","value") within Java code. */ properties.addConfiguration(new SystemConfiguration()); /** * User specific options are 3rd. */ String filename = System.getProperty("user.home") + File.separator + ".ffx/ffx.properties"; File userPropFile = new File(filename); if (userPropFile.exists() && userPropFile.canRead()) { try { properties.addConfiguration(new PropertiesConfiguration(userPropFile)); } catch (ConfigurationException e) { logger.log(Level.INFO, " Error loading {0}.", filename); } } /** * System wide options are 2nd to last. */ filename = System.getenv("FFX_PROPERTIES"); if (filename != null) { File systemPropFile = new File(filename); if (systemPropFile.exists() && systemPropFile.canRead()) { try { properties.addConfiguration(new PropertiesConfiguration(systemPropFile)); } catch (ConfigurationException e) { logger.log(Level.INFO, " Error loading {0}.", filename); } } } /** * Echo the interpolated configuration. */ if (logger.isLoggable(Level.FINE)) { //Configuration config = properties.interpolatedConfiguration(); Iterator<String> i = properties.getKeys(); StringBuilder sb = new StringBuilder(); sb.append(String.format("\n %-30s %s\n", "Property", "Value")); while (i.hasNext()) { String s = i.next(); //sb.append(String.format(" %-30s %s\n", s, Arrays.toString(config.getList(s).toArray()))); sb.append(String.format(" %-30s %s\n", s, Arrays.toString(properties.getList(s).toArray()))); } logger.fine(sb.toString()); } return properties; }
From source file:com.symbian.driver.core.ResourceLoader.java
/** * Loads any type of TestDriver file including v1 and v2. * //from w w w . j a v a 2 s .co m * @return The EMF task that is loaded. * @throws ParseException If a configuration error has occured. */ public static Task load() throws ParseException { Task lTask = null; TDConfig CONFIG = TDConfig.getInstance(); URI lAddressURI = CONFIG.getPreferenceURI(TDConfig.ENTRY_POINT_ADDRESS); try { // ONLY a.driver exits if (lAddressURI.fileExtension() == null) { // CASE: -s b.c.d OR -s a.b.c.d File lXmlRoot = CONFIG.getPreferenceFile(TDConfig.XML_ROOT); String lAddressString = lAddressURI.toString(); int lFirstDotInAddress = (lAddressString.indexOf('.') > 0) ? lAddressString.indexOf('.') : lAddressString.length(); File lPotentialDriverFile = new File(lXmlRoot.getCanonicalPath(), lAddressString.substring(1, lFirstDotInAddress).concat(".driver")); File lDriverFiles[] = null; // only get the File is the first IF // fails. if (lPotentialDriverFile.isFile()) { // CASE: -s a.b.c.d then a.driver exists URI lDriverURI = URI.createFileURI(lPotentialDriverFile.getCanonicalPath()); lDriverURI = lDriverURI.appendFragment(lAddressString.substring(1)); LOGGER.info("Using new XML: " + lPotentialDriverFile + " from XMLRoot " + lXmlRoot + " instead of the old XMLRoot."); CONFIG.setPreferenceURI(TDConfig.ENTRY_POINT_ADDRESS, lDriverURI); lTask = load(lDriverURI); } else if (lXmlRoot.isDirectory() && (lDriverFiles = Utils.getFilesWithExtension(lXmlRoot, ".driver")).length == 1) { // CASE: -s b.c.d and b.driver doesn't exist but a.driver // does exist File lDriverFile = lDriverFiles[0]; String lDriverName = lDriverFile.getName(); URI lDriverURI = URI.createFileURI(lDriverFile.getCanonicalPath()); lDriverURI = lDriverURI.appendFragment( lDriverName.substring(0, lDriverName.indexOf('.') + 1) + lAddressString.substring(1)); lTask = load(lDriverURI); } else if (lXmlRoot.isDirectory() && Utils.getFilesWithExtension(lXmlRoot, ".xml").length > 0) { // CASE: -s b.c.d or a.b.c.d but no .driver file lTask = loadOldXml(lXmlRoot, lAddressURI); } else { throw new IOException( "Could not find a .driver file nor .xml files in: " + lXmlRoot.getCanonicalPath()); } } else if (lAddressURI.fileExtension().equalsIgnoreCase("driver")) { // CASE: -s file:/a.driver lTask = load(lAddressURI); } else { // CASE: doesn't end with .driver but with another extension throw new IOException("Please use the extension .driver"); } return lTask; } catch (FileNotFoundException lFileNotFoundException) { LOGGER.log(Level.SEVERE, "Could not find the file corresponding to: " + lAddressURI, lFileNotFoundException); } catch (IOException lIOException) { LOGGER.log(Level.SEVERE, "Could not open the file corresponding to: " + lAddressURI, lIOException); } return null; }
From source file:it.uniud.ailab.dcore.wrappers.external.OpenNlpBootstrapperAnnotator.java
/** * Checks if the database entry for the POStagger are local or web resources * and downloads the online ones.// ww w . j a v a 2 s . c o m * */ private static void prepareModels() { Map<String, String> correctPaths = new HashMap<>(); for (Map.Entry e : databasePaths.entrySet()) { String entryKey = (String) e.getKey(); String entryValue = (String) e.getValue(); try { URL url = new URL((String) e.getValue()); // if we're dealing with a local file, then // we don't care and continue. if (isLocalFile(url)) { Logger.getLogger(OpenNlpBootstrapperAnnotator.class.getName()).log(Level.INFO, "Using {0} as local path...", e.getValue()); continue; } // Download the new file and put it in a local folder String newFileName = FileSystem.getDistillerTmpPath().concat(FileSystem.getSeparator()) .concat("OpenNLPmodels").concat(FileSystem.getSeparator()).concat(url.getPath() .substring(url.getPath().lastIndexOf("/") + 1, url.getPath().length())); ; // Check if the file already exists (i.e. we have probably // downloaded it before). If exists, then we're happy and // don't download anything File f = new File(newFileName); if (f.exists()) { //LOG.log(Level.INFO, "Using {0} as local cache...", newFileName); correctPaths.put(entryKey, f.getCanonicalPath()); continue; } Logger.getLogger(OpenNlpBootstrapperAnnotator.class.getName()).log(Level.INFO, "Downloading model from {0}...", e.getValue()); FileUtils.copyURLToFile(url, f); Logger.getLogger(OpenNlpBootstrapperAnnotator.class.getName()).log(Level.INFO, "OpenNLP database saved in {0}", f.getCanonicalPath()); correctPaths.put(entryKey, f.getAbsolutePath()); } catch (MalformedURLException ex) { //LOG.log(Level.INFO, "Using {0} as local path...", e.getValue()); } catch (IOException ex) { //LOG.log(Level.SEVERE, "Savefile error", ex); throw new AnnotationException(new OpenNlpBootstrapperAnnotator(), "Failed to download " + e.getValue(), ex); } finally { // if something went wrong, put the default value. if (!correctPaths.containsKey(entryKey)) { correctPaths.put(entryKey, entryValue); } } } // update the old map with the new values databasePaths.clear(); databasePaths.putAll(correctPaths); }
From source file:eu.eubrazilcc.lvl.core.io.FileCompressor.java
/** * Uncompress the content of a tarball file to the specified directory. * @param srcFile - the tarball to be uncompressed * @param outDir - directory where the files (and directories) extracted from the tarball will be written * @return the list of files (and directories) extracted from the tarball * @throws IOException when an exception occurs on uncompressing the tarball *//*from www. j av a2 s . co m*/ public static List<String> unGzipUnTar(final String srcFile, final String outDir) throws IOException { final List<String> uncompressedFiles = newArrayList(); FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; GzipCompressorInputStream gzipCompressorInputStream = null; TarArchiveInputStream tarArchiveInputStream = null; BufferedInputStream bufferedInputStream2 = null; try { forceMkdir(new File(outDir)); fileInputStream = new FileInputStream(srcFile); bufferedInputStream = new BufferedInputStream(fileInputStream); gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream); TarArchiveEntry entry = null; while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) { final File outputFile = new File(outDir, entry.getName()); if (entry.isDirectory()) { // attempting to write output directory if (!outputFile.exists()) { // attempting to create output directory if (!outputFile.mkdirs()) { throw new IOException("Cannot create directory: " + outputFile.getCanonicalPath()); } } } else { // attempting to create output file final byte[] content = new byte[(int) entry.getSize()]; tarArchiveInputStream.read(content, 0, content.length); final FileOutputStream outputFileStream = new FileOutputStream(outputFile); write(content, outputFileStream); outputFileStream.close(); uncompressedFiles.add(outputFile.getCanonicalPath()); } } } finally { if (bufferedInputStream2 != null) { bufferedInputStream2.close(); } if (tarArchiveInputStream != null) { tarArchiveInputStream.close(); } if (gzipCompressorInputStream != null) { gzipCompressorInputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } if (fileInputStream != null) { fileInputStream.close(); } } return uncompressedFiles; }
From source file:org.biopax.validator.Main.java
public static Collection<Resource> getResourcesToValidate(String input) throws IOException { Set<Resource> setRes = new HashSet<Resource>(); File fileOrDir = new File(input); if (fileOrDir.isDirectory()) { // validate all the OWL files in the folder FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.endsWith(".owl")); }/*from w w w . jav a2 s.c o m*/ }; for (String s : fileOrDir.list(filter)) { String uri = "file:" + fileOrDir.getCanonicalPath() + File.separator + s; setRes.add(ctx.getResource(uri)); } } else if (input.startsWith("list:")) { // consider it's a file that contains a list of (pseudo-)URLs String batchFile = input.replaceFirst("list:", "file:"); Reader isr = new InputStreamReader(ctx.getResource(batchFile).getInputStream()); BufferedReader reader = new BufferedReader(isr); String line; while ((line = reader.readLine()) != null && !"".equals(line.trim())) { // check the source URL if (!ResourceUtils.isUrl(line)) { log.error("Invalid URL: " + line + ". A resource must be either a " + "pseudo URL (classpath: or file:) or standard URL!"); continue; } setRes.add(ctx.getResource(line)); } reader.close(); } else { // a single local OWL file or remote data Resource resource = null; if (!ResourceUtils.isUrl(input)) input = "file:" + input; resource = ctx.getResource(input); setRes.add(resource); } return setRes; }
From source file:eu.europeana.enrichment.common.Utils.java
public static List<File> expandFileTemplateFrom(File dir, String... pattern) throws IOException { List<File> files = new ArrayList<File>(); for (String p : pattern) { File fdir = new File(new File(dir, FilenameUtils.getFullPathNoEndSeparator(p)).getCanonicalPath()); if (!fdir.isDirectory()) throw new IOException("Error: " + fdir.getCanonicalPath() + ", expanded from directory " + dir.getCanonicalPath() + " and pattern " + p + " does not denote a directory"); if (!fdir.canRead()) throw new IOException("Error: " + fdir.getCanonicalPath() + " is not readable"); FileFilter fileFilter = new WildcardFileFilter(FilenameUtils.getName(p)); File[] list = fdir.listFiles(fileFilter); if (list == null) throw new IOException("Error: " + fdir.getCanonicalPath() + " does not denote a directory or something else is wrong"); if (list.length == 0) throw new IOException("Error: no files found, template " + p + " from dir " + dir.getCanonicalPath() + " where we recognised " + fdir.getCanonicalPath() + " as path and " + fileFilter + " as file mask"); for (File file : list) { if (!file.exists()) { throw new FileNotFoundException( "File not found: " + file + " resolved to " + file.getCanonicalPath()); }/*from w ww . ja v a 2 s . co m*/ } files.addAll(Arrays.asList(list)); } return files; }