List of usage examples for java.io File canRead
public boolean canRead()
From source file:com.dumontierlab.pdb2rdf.Pdb2Rdf.java
private static Pdb2RdfInputIterator processInput(CommandLine cmd) { boolean gzip = cmd.hasOption("gzip"); try {/*from w w w . j a v a 2s. c o m*/ if (cmd.hasOption("file")) { File file = new File(cmd.getOptionValue("file")); if (!file.exists() || !file.canRead()) { LOG.fatal("Cannot access file: " + file); System.exit(1); } return new Pdb2RdfInputIteratorAdapter(new FileIterator(file, gzip)); } else if (cmd.hasOption("dir")) { File dir = new File(cmd.getOptionValue("dir")); if (!dir.exists() || !dir.canRead() || !dir.canExecute()) { LOG.fatal("Cannot access directory: " + dir); System.exit(1); } return new Pdb2RdfInputIteratorAdapter(new DirectoryIterator(dir, gzip)); } else if (cmd.hasOption("cluster")) { String url = cmd.getOptionValue("cluster"); return new ClusterIterator(url); } else { String[] args = cmd.getArgs(); if (args.length == 0) { LOG.fatal( "You need to specified the file option, the dir option, or explicitly list the pdb ids."); printUsage(); System.exit(1); } return new PdbsIterator(args); } } catch (Exception e) { LOG.fatal(e); System.exit(1); return null; } }
From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java
private static byte[] loadSWTLibrary() throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { String name = getOSName();//from w ww . ja v a 2s. co m if (name == null) throw new IllegalArgumentException("Cannot determine OS"); String arch = getArch(); if (arch == null) throw new IllegalArgumentException("Cannot determine architecture"); String artifactId = "org.eclipse.swt." + name + "." + arch; String swtLocation = artifactId + "-" + SWT_VERSION + ".jar"; System.out.println("Loading SWT version " + swtLocation); byte[] data = null; File savedJar = new File(Constants.DATA_DIR, swtLocation); if (savedJar.isDirectory() && !savedJar.delete()) throw new IllegalArgumentException("Saved file is a directory and could not be deleted"); if (savedJar.exists() && savedJar.canRead()) { try { System.out.println("Loading from saved file"); InputStream inputStream = new FileInputStream(savedJar); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(inputStream, outputStream); data = outputStream.toByteArray(); } catch (IOException exception) { System.out.println("Failed to load from saved file."); exception.printStackTrace(System.out); } } if (data == null) { InputStream fromJar = Bootloader.class.getResourceAsStream("/swt/" + swtLocation); if (fromJar != null) { try { System.out.println("Loading from within JAR"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(fromJar, outputStream); data = outputStream.toByteArray(); } catch (IOException exception) { System.out.println("Failed to load within JAR"); exception.printStackTrace(System.out); } } } if (data == null) { URL url = new URL("https://maven-eclipse.github.io/maven/org/eclipse/swt/" + artifactId + "/" + SWT_VERSION + "/" + swtLocation); try { System.out.println("Loading over the internet"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() == 200) { InputStream fromURL = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); copy(fromURL, outputStream); data = outputStream.toByteArray(); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } } catch (IOException exception) { System.out.println("Failed to load over the internet"); exception.printStackTrace(System.out); } } if (data == null) { throw new IllegalArgumentException("Failed to load SWT"); } if (!savedJar.exists()) { try { System.out.println("Writing to saved file"); if (savedJar.createNewFile()) { FileOutputStream fileOutputStream = new FileOutputStream(savedJar); fileOutputStream.write(data); fileOutputStream.close(); } else { throw new IOException("Could not create new file"); } } catch (IOException exception) { System.out.println("Failed to write to saved file"); exception.printStackTrace(System.out); } } byte[] dd = data; URL.setURLStreamHandlerFactory(protocol -> { //JarInJar! if (protocol.equals("swt")) { return new URLStreamHandler() { protected URLConnection openConnection(URL u) { return new URLConnection(u) { public void connect() { } public InputStream getInputStream() { return new ByteArrayInputStream(dd); } }; } protected void parseURL(URL u, String spec, int start, int limit) { // Don't parse or it's too slow } }; } return null; }); ClassLoader classLoader = Bootloader.class.getClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(classLoader, new URL("swt://load")); return data; }
From source file:com.urbancode.terraform.main.Main.java
/** * Creates a file and runs checks on it/* w ww . ja va 2 s. com*/ * * @param filePath * @return * @throws FileNotFoundException */ static private File createFile(String filePath) throws FileNotFoundException { File result = null; if (!"".equals(filePath)) { result = new File(filePath); if (result.exists()) { if (result.isFile()) { if (!result.canRead()) { String msg = "Input file does not exist: " + filePath; log.fatal(msg); throw new FileNotFoundException(msg); } } else { String msg = "Input file is not a file: " + filePath; log.fatal(msg); throw new FileNotFoundException(msg); } } else { String msg = "Input file does not exist: " + filePath; log.fatal(msg); throw new FileNotFoundException(msg); } } return result; }
From source file:FileStatus.java
public static void status(String fileName) throws IOException { System.out.println("---" + fileName + "---"); // Construct a File object for the given file. File f = new File(fileName); // See if it actually exists if (!f.exists()) { System.out.println("file not found"); System.out.println(); // Blank line return;/*w ww . j a v a 2s . com*/ } // Print full name System.out.println("Canonical name " + f.getCanonicalPath()); // Print parent directory if possible String p = f.getParent(); if (p != null) { System.out.println("Parent directory: " + p); } // Check if the file is readable if (f.canRead()) { System.out.println("File is readable."); } // Check if the file is writable if (f.canWrite()) { System.out.println("File is writable."); } // Report on the modification time. Date d = new Date(); d.setTime(f.lastModified()); System.out.println("Last modified " + d); // See if file, directory, or other. If file, print size. if (f.isFile()) { // Report on the file's size System.out.println("File size is " + f.length() + " bytes."); } else if (f.isDirectory()) { System.out.println("It's a directory"); } else { System.out.println("I dunno! Neither a file nor a directory!"); } System.out.println(); // blank line between entries }
From source file:dk.netarkivet.common.utils.ZipUtils.java
/** Unzip a zipFile into a directory. This will create subdirectories * as needed./*from w w w. j a v a2s .c o m*/ * * @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:Cresendo.java
private static void checkConfigFile(String cfgFile) { File f = new File(cfgFile); if (!f.exists()) { System.err.println("Error: File does not exist: " + cfgFile); System.exit(1);/*from www .j a va 2 s . co m*/ } if (!f.canRead()) { System.err.println("Error: Unable to read file: " + cfgFile); System.exit(1); } }
From source file:com.kegare.caveworld.world.WorldProviderCaveworld.java
private static NBTTagCompound readDimData() { NBTTagCompound data;//from ww w . j a va2 s . com File dir = getDimDir(); if (dir == null) { data = null; } else { File file = new File(dir, "caveworld.dat"); if (!file.exists() || !file.isFile() || !file.canRead()) { data = null; } else try (FileInputStream input = new FileInputStream(file)) { data = CompressedStreamTools.readCompressed(input); } catch (Exception e) { CaveLog.log(Level.ERROR, e, "An error occurred trying to reading Caveworld dimension data"); data = null; } } return data == null ? new NBTTagCompound() : data; }
From source file:com.openkm.util.impexp.DbRepositoryChecker.java
/** * Read document contents./*from w ww .j a v a 2 s. c o m*/ */ @SuppressWarnings("resource") private static ImpExpStats readDocument(String token, String docPath, boolean fast, boolean versions, boolean checksum, Writer out, InfoDecorator deco) throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException, IOException { log.debug("readDocument({}, {}, {}, {})", new Object[] { docPath, fast, versions, checksum }); long begin = System.currentTimeMillis(); DocumentModule dm = ModuleManager.getDocumentModule(); File fsTmp = FileUtils.createTempFile(); FileOutputStream fosTmp = null; InputStream is = null; ImpExpStats stats = new ImpExpStats(); Document doc = dm.getProperties(token, docPath); String curVerName = null; try { String docUuid = NodeBaseDAO.getInstance().getUuidFromPath(docPath); if (Config.REPOSITORY_NATIVE && FsDataStore.DATASTORE_BACKEND_FS.equals(Config.REPOSITORY_DATASTORE_BACKEND) && fast) { NodeDocumentVersion nDocVer = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid); File dsDocVerFile = FsDataStore.resolveFile(nDocVer.getUuid()); if (!dsDocVerFile.exists()) { throw new IOException("File does not exists: " + dsDocVerFile); } else if (!dsDocVerFile.canRead()) { throw new IOException("Can't read file: " + dsDocVerFile); } } else { fosTmp = new FileOutputStream(fsTmp); is = dm.getContent(token, docPath, false); IOUtils.copy(is, fosTmp); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fosTmp); } if (Config.REPOSITORY_NATIVE && Config.REPOSITORY_CONTENT_CHECKSUM && checksum) { curVerName = NodeDocumentVersionDAO.getInstance().findCurrentVersionName(docUuid); FsDataStore.verifyChecksum(docUuid, curVerName, fsTmp); } if (versions) { // Check version history if (curVerName == null) { curVerName = NodeDocumentVersionDAO.getInstance().findCurrentVersionName(docUuid); } for (Version ver : dm.getVersionHistory(token, docPath)) { if (!curVerName.equals(ver.getName())) { if (Config.REPOSITORY_NATIVE && FsDataStore.DATASTORE_BACKEND_FS.equals(Config.REPOSITORY_DATASTORE_BACKEND) && fast) { NodeDocumentVersion nDocVer = NodeDocumentVersionDAO.getInstance().findVersion(docUuid, ver.getName()); File dsDocVerFile = FsDataStore.resolveFile(nDocVer.getUuid()); if (!dsDocVerFile.exists()) { throw new IOException( "File does not exists: " + dsDocVerFile + ", version: " + ver.getName()); } else if (!dsDocVerFile.canRead()) { throw new IOException( "Can't read file: " + dsDocVerFile + ", version: " + ver.getName()); } } else { is = dm.getContentByVersion(token, docPath, ver.getName()); fosTmp = new FileOutputStream(fsTmp); IOUtils.copy(is, fosTmp); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fosTmp); if (Config.REPOSITORY_NATIVE && Config.REPOSITORY_CONTENT_CHECKSUM && checksum) { FsDataStore.verifyChecksum(docUuid, ver.getName(), fsTmp); } } } } FileLogger.info(BASE_NAME, "Checked document version ''{0} - {1}''", docPath, curVerName); } out.write(deco.print(docPath, doc.getActualVersion().getSize(), null)); out.flush(); // Stats stats.setSize(stats.getSize() + doc.getActualVersion().getSize()); stats.setDocuments(stats.getDocuments() + 1); FileLogger.info(BASE_NAME, "Checked document ''{0}''", docPath); } catch (RepositoryException e) { log.error(e.getMessage()); stats.setOk(false); FileLogger.error(BASE_NAME, "RepositoryException ''{0}''", e.getMessage()); out.write(deco.print(docPath, doc.getActualVersion().getSize(), e.getMessage())); out.flush(); } catch (IOException e) { log.error(e.getMessage()); stats.setOk(false); FileLogger.error(BASE_NAME, "IOException ''{0}''", e.getMessage()); out.write(deco.print(docPath, doc.getActualVersion().getSize(), e.getMessage())); out.flush(); } catch (Exception e) { log.error(e.getMessage()); stats.setOk(false); FileLogger.error(BASE_NAME, "Exception ''{0}''", e.getMessage()); out.write(deco.print(docPath, doc.getActualVersion().getSize(), e.getMessage())); out.flush(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fosTmp); org.apache.commons.io.FileUtils.deleteQuietly(fsTmp); } log.trace("readDocument.Time: {}", System.currentTimeMillis() - begin); return stats; }
From source file:edu.stanford.muse.util.ThunderbirdUtils.java
private static String getThunderbirdProfileDir() { String tbirdDir = System.getProperty("user.home"); boolean isMac = false; boolean isWindowsXP = false; boolean isWindowsVistaOr7 = false; boolean isLinux = false; // if (userAgent == null) // userAgent = ""; // userAgent = userAgent.toLowerCase(); String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("mac")) isMac = true;/*from www .j a v a 2 s . com*/ else if (os.indexOf("linux") >= 0 || os.indexOf("solaris") >= 0 || os.indexOf("hp-ux") >= 0) isLinux = true; else if (os.startsWith("windows")) { if (os.endsWith("xp")) isWindowsXP = true; else // if (os.endsWith("vista)) isWindowsVistaOr7 = true; } // if (userAgent.indexOf("macintosh") >= 0 || userAgent.indexOf("mac os") >= 0) // isMac = true; // else if (userAgent.indexOf("linux") >= 0) // isLinux = true; // else // isWindows = true; // // // special hack for xp // if (homeDir.indexOf("Documents and Settings") >= 0) // { // tbirdDir += "\\Application Data\\Thunderbird\\Profiles"; // isWindows = true; // } // else // { // if (isMac) // tbirdDir += "/Library/Thunderbird/Profiles"; // else if (isWindows) // tbirdDir += "\\AppData\\Roaming\\Thunderbird\\Profiles"; // vista, win7 // else if (isLinux) // tbirdDir += "/.thunderbird"; // } // tbirdDir += "\\Application Data\\Thunderbird\\Profiles"; if (isMac) tbirdDir += "/Library/Thunderbird/Profiles"; else if (isWindowsVistaOr7) tbirdDir += "\\AppData\\Roaming\\Thunderbird\\Profiles"; // vista, win7 else if (isWindowsXP) tbirdDir += "\\Application Data\\Thunderbird\\Profiles"; // vista, win7 else if (isLinux) tbirdDir += "/.thunderbird"; File tbirdFile = new File(tbirdDir); if (!tbirdFile.exists() || !tbirdFile.canRead()) return ""; // look for a file *.default - doing wildcard manually File[] files = tbirdFile.listFiles(); String defaultFolderName = null; for (File f : files) if (f.isDirectory()) if (f.getName().endsWith(".default")) { defaultFolderName = f.getName(); break; } if (defaultFolderName != null) { tbirdDir += File.separator + defaultFolderName; // tbirdDir += File.separator + "Mail" + File.separator + "Local Folders"; } log.debug("thunderbird dir is " + tbirdDir); return tbirdDir; }
From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java
/** * Lists the GenBank sequences found in the specified directory (subdirectories are not searched). * @param directory - the directory to search for sequences in * @return /*from w ww . jav a 2s . c om*/ */ public static Collection<File> listGBFiles(final File directory, final Format format) { checkArgument(directory != null && directory.isDirectory() && directory.canRead(), "Uninitialized or invalid directory"); String extension; switch (format) { case GB_SEQ_XML: extension = "xml"; break; case FLAT_FILE: extension = "gb"; break; default: extension = null; break; } checkArgument(isNotBlank(extension), "Unsupported GenBank format: " + format); return listFiles(directory, new String[] { extension }, false); }