List of usage examples for java.io File canRead
public boolean canRead()
From source file:com.emental.mindraider.core.search.SearchCommander.java
/** * Index documents./* w w w. j av a 2 s . c om*/ * * @param writer * the index writer * @param file * the file to write * @param rebuildSearchIndexJDialog * the rebuild search index JDialog * @throws IOException * the I/O exception */ public static void indexDocs(IndexWriter writer, File file) throws IOException { // do not try to index files that cannot be read if (file.canRead()) { if (file.isDirectory()) { String[] files = file.list(); // an IO error could occur if (files != null) { for (String filename : files) { indexDocs(writer, new File(file, filename)); } } } else { StatusBar.setText(action, file.getAbsolutePath(), 70); try { // I'm interested only in indexing of concepts if (file.getAbsolutePath() .indexOf(File.separator + CONCEPTS_DIRECTORY_NAME + File.separator) >= 0) { ConceptResource conceptResource = new ConceptResource(new Resource(file.getAbsolutePath())); // FTS index // TODO parse notebook label from the path for now String notebookUri = conceptResource.getNotebookUri(); String notebookLabel; if (notebookUri != null && (notebookUri.indexOf("#") >= 0)) { // TODO from time to time the last letter is killed notebookLabel = notebookUri.substring(notebookUri.indexOf("#") + 1, notebookUri.length()); // TODO ugly hack - label must be loaded from the model (slow) notebookLabel = notebookLabel.replaceAll("_", " "); } else { notebookLabel = "Notebook"; } // tag (infiltrated) CategoryProperty[] tagsAndFlag = conceptResource.getCategories(); if (tagsAndFlag != null && tagsAndFlag.length > 0) { for (CategoryProperty tagOrFlag : tagsAndFlag) { // only tags (not the flag!) are indexed if (tagOrFlag.getCategoryValue() != null && tagOrFlag.getCategoryValue().length() > 0) { if (!tagOrFlag.getCategoryValue() .startsWith(MindRaiderConstants.MR_OWL_FLAG_NS)) { MindRaider.tagCustodian.addOrInc( new TagEntryImpl(tagOrFlag.getCategoryValue(), tagOrFlag.getCategoryCaption(), 1), new TaggedResourceEntry(notebookUri, notebookLabel, conceptResource.getUri(), conceptResource.getLabel(), conceptResource.resource.getMetadata().getTimestamp(), file.getAbsoluteFile().getAbsolutePath())); } } } } // write it to index writer.addDocument(FileDocument.Document(file, notebookLabel, conceptResource.getLabel(), conceptResource.getUri())); } } catch (EOFException e) { logger.debug("Unable to read file " + file.getAbsolutePath(), e); } // at least on windows, some temporary files raise this // exception with an "access denied" message // checking if the file can be read doesn't help catch (Exception e) { logger.debug("File not found!", e); } } } }
From source file:it.cnr.icar.eric.client.xml.registry.util.KeystoreUtil.java
/** * Returns if keystore file can be read, throws an exception otherwise * * @param keystoreFile Path to keystore file * @throws JAXRException Thrown if keystore file can not be read *///from w ww. jav a2 s . c om public static void canReadKeystoreFile(File keystoreFile) throws JAXRException { try { if (!keystoreFile.exists()) { throw new JAXRException(JAXRResourceBundle.getInstance().getString( "message.error.keystore.file.not.exist", new Object[] { keystoreFile.getAbsolutePath() })); } if (!keystoreFile.canRead()) { throw new JAXRException(JAXRResourceBundle.getInstance().getString( "message.error.read.keysore.file", new Object[] { keystoreFile.getAbsolutePath() })); } } catch (SecurityException e) { log.error(e); throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.error.read.keysore.file", new Object[] { keystoreFile.getAbsolutePath() })); } }
From source file:com.dnielfe.manager.utils.SimpleUtils.java
@NotNull public static ArrayList<String> listFiles(String path) { ArrayList<String> mDirContent = new ArrayList<String>(); boolean showhidden = Settings.mShowHiddenFiles; if (!mDirContent.isEmpty()) mDirContent.clear();//w w w .j ava 2 s. c o m final File file = new File(path); if (file.exists() && file.canRead()) { String[] list = file.list(); int len = list.length; // add files/folder to ArrayList depending on hidden status for (int i = 0; i < len; i++) { if (!showhidden) { if (list[i].toString().charAt(0) != '.') mDirContent.add(path + "/" + list[i]); } else { mDirContent.add(path + "/" + list[i]); } } } else { try { mDirContent = RootCommands.listFiles(file.getAbsolutePath(), showhidden); } catch (Exception e) { e.printStackTrace(); } } // sort files with a comparator SortUtils.sortList(mDirContent, file.getPath()); return mDirContent; }
From source file:com.ikon.util.ExecutionUtils.java
/** * Execute script from file/*w w w.j a v a 2 s . c om*/ * * @return 0 - Return * 1 - StdOut * 2 - StdErr */ public static Object[] runScript(File script) throws EvalError { Object[] ret = new Object[3]; FileReader fr = null; try { if (script.exists() && script.canRead()) { ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baosOut); ByteArrayOutputStream baosErr = new ByteArrayOutputStream(); PrintStream err = new PrintStream(baosErr); Interpreter i = new Interpreter(null, out, err, false); fr = new FileReader(script); ret[0] = i.eval(fr); out.flush(); ret[1] = baosOut.toString(); err.flush(); ret[2] = baosErr.toString(); } else { log.warn("Unable to read script: {}", script.getPath()); } } catch (IOException e) { log.warn(e.getMessage(), e); } finally { IOUtils.closeQuietly(fr); } log.debug("runScript: {}", Arrays.toString(ret)); return ret; }
From source file:net.community.chest.gitcloud.facade.ConfigUtils.java
/** * Checks that a give property value that represents a folder is valid as follows:</BR> * <UL>/*from ww w .j a va2 s.c o m*/ * <LI>If exists, then it must be a folder with read/write/execute permissions</LI> * <LI>Otherwise, it is created along with its parents</LI> * <UL> * @param propName The property name (used for meaningful exception message) * @param propValue The {@link File} to verify * @return <code>false</code> if this is an already existing folder, <code>true</code> * if had to create it (and its parents) * @throws IllegalStateException if any of the validation tests fails * @see File#mkdirs() */ public static final boolean verifyFolderProperty(String propName, File propValue) throws IllegalStateException { if (propValue.exists()) { if (!propValue.isDirectory()) { throw new IllegalStateException("verifyFolderProperty(" + propName + ") not a folder: " + ExtendedFileUtils.toString(propValue)); } if (!propValue.canRead()) { throw new IllegalStateException("verifyFolderProperty(" + propName + ") non-readable: " + ExtendedFileUtils.toString(propValue)); } if (!propValue.canWrite()) { throw new IllegalStateException("verifyFolderProperty(" + propName + ") non-writeable: " + ExtendedFileUtils.toString(propValue)); } if (!propValue.canExecute()) { throw new IllegalStateException("verifyFolderProperty(" + propName + ") non-listable: " + ExtendedFileUtils.toString(propValue)); } return false; } else { if (!propValue.mkdirs()) { throw new IllegalStateException("verifyFolderProperty(" + propName + ") failed to create: " + ExtendedFileUtils.toString(propValue)); } return true; } }
From source file:ch.admin.suis.msghandler.util.FileUtils.java
/** * Returns/*from ww w . j a v a 2s. co m*/ * <code>true</code>, if the given file can be read by the application. This methods tries to acquire a shared lock * over the specified file. This lock is then immediately released. if an error occurs while acuiring the lock, this * method returns * <code>false</code>. * * @param pathname The path to the file * @return boolean. True if the file can be read, false otherwise. */ public static boolean canRead(File pathname) { if (!pathname.canRead()) { return false; } try (FileInputStream fis = new FileInputStream(pathname)) { FileLock lock = fis.getChannel().tryLock(0, Long.MAX_VALUE, true); if (lock != null) { // do not hold the lock lock.release(); return true; } else { LOG.info("cannot lock the file " + pathname.getAbsolutePath() + "; it is probably locked by another application"); return false; } } catch (IOException e) { LOG.error("an exception occured while trying to acquire lock on the file " + pathname.getAbsolutePath(), e); return false; } }
From source file:ffx.utilities.Keyword.java
/** * This method sets up configuration properties in the following precedence * * order:/*from www .j a v a 2s .c o m*/ * * 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.tc.process.Exec.java
private static void ensureDir(File dir) { if (!dir.exists()) { throw new AssertionError(dir + " does not exist"); }/* ww w . j a v a2s. co m*/ if (!dir.isDirectory()) { throw new AssertionError(dir + " is not a directory"); } if (!dir.canRead()) { throw new AssertionError(dir + " is not readable"); } }
From source file:com.sketchy.utils.image.SketchyImage.java
public static SketchyImage load(File file) throws Exception { SketchyImage sketchyImage = null;/* w w w.j a v a 2s. c om*/ if (!file.exists() || !file.canRead()) { throw new Exception("Can not find or read File: " + file.getPath() + "!"); } if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) { throw new Exception("Can not load SketchyImage! Must be a .png file!"); } Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png"); ImageReader imageReader = null; if (imageReaders.hasNext()) { // Just get first one imageReader = imageReaders.next(); } if (imageReader == null) { // this should never happen!! if so.. we got problems throw new Exception("Can not find ImageReader for .png Files!"); } ImageInputStream is = null; try { is = ImageIO.createImageInputStream(file); imageReader.setInput(is, true); IIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData .getAsTree(metaData.getNativeMetadataFormatName()); if (metaDataNode == null) { throw new Exception("Error retreiving MetaData properties from .png File!"); } NodeList childNodes = metaDataNode.getElementsByTagName("pHYs"); // only look in the first node if (childNodes.getLength() == 0) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!"); } IIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0); String pixelsPerUnitXAxisAttribute = physNode.getAttribute("pixelsPerUnitXAxis"); String pixelsPerUnitYAxisAttribute = physNode.getAttribute("pixelsPerUnitYAxis"); // String unitSpecifierAttribute = physNode.getAttribute("unitSpecifier"); Just assuming meter if (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!"); } if (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!"); } int pixelsPerUnitXAxis; try { pixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute); if (pixelsPerUnitXAxis <= 0) throw new Exception("Value must be > 0"); } catch (Exception e) { throw new Exception("Invalid 'pixelsPerUnitXAxis' MetaData Attribute! " + e.getMessage()); } int pixelsPerUnitYAxis; try { pixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute); if (pixelsPerUnitYAxis <= 0) throw new Exception("Value must be > 0"); } catch (Exception e) { throw new Exception("Invalid 'pixelsPerUnitYAxis' MetaData Attribute! " + e.getMessage()); } // We successfully processed the MetaData.. now read/set the image BufferedImage bufferedImage = imageReader.read(0); // always get first image double xPixelsPerMM = pixelsPerUnitXAxis / 1000.0; double yPixelsPerMM = pixelsPerUnitYAxis / 1000.0; sketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM); } catch (Exception e) { throw new Exception("Error Loading SketchyImage File: " + file.getPath() + "! " + e.getMessage()); } finally { IOUtils.closeQuietly(is); } return sketchyImage; }
From source file:net.sf.webphotos.tools.Thumbnail.java
/** * Cria thumbs para as imagens. Testa se j existem valores setados para o * thumb, se no existir chama o mtodo//from w w w . j a v a 2s . co m * {@link net.sf.webphotos.Thumbnail#inicializar() inicializar} para setar * seus valores. Abre o arquivo de imagem passado como parmetro e checa se * uma foto vlida. Obtm o tamanho original da imagem, checa se est no * formato paisagem ou retrato e utiliza o mtodo * {@link java.awt.Image#getScaledInstance(int,int,int) getScaledInstance} * para calcular os thumbs. Ao final, salva as imagens. * * @param caminhoCompletoImagem Caminho da imagem. */ public static void makeThumbs(String caminhoCompletoImagem) { String diretorio, arquivo; if (t1 == 0) { inicializar(); } try { File f = new File(caminhoCompletoImagem); if (!f.isFile() || !f.canRead()) { Util.err.println("[Thumbnail.makeThumbs]/ERRO: Erro no caminho do arquivo " + caminhoCompletoImagem + " incorreto"); return; } // Foto em alta corrompida if (getFormatName(f) == null) { Util.err.println("[Thumbnail.makeThumbs]/ERRO: Foto Corrompida"); return; } else { Util.out.println("[Thumbnail.makeThumbs]/INFO: Foto Ok!"); } diretorio = f.getParent(); arquivo = f.getName(); ImageIcon ii = new ImageIcon(f.getCanonicalPath()); Image i = ii.getImage(); Image tumb1, tumb2, tumb3, tumb4; // obtm o tamanho da imagem original int iWidth = i.getWidth(null); int iHeight = i.getHeight(null); //int w, h; if (iWidth > iHeight) { tumb1 = i.getScaledInstance(t1, (t1 * iHeight) / iWidth, Image.SCALE_SMOOTH); tumb2 = i.getScaledInstance(t2, (t2 * iHeight) / iWidth, Image.SCALE_SMOOTH); tumb3 = i.getScaledInstance(t3, (t3 * iHeight) / iWidth, Image.SCALE_SMOOTH); tumb4 = i.getScaledInstance(t4, (t4 * iHeight) / iWidth, Image.SCALE_SMOOTH); //w = t4; //h = (t4 * iHeight) / iWidth; } else { tumb1 = i.getScaledInstance((t1 * iWidth) / iHeight, t1, Image.SCALE_SMOOTH); tumb2 = i.getScaledInstance((t2 * iWidth) / iHeight, t2, Image.SCALE_SMOOTH); tumb3 = i.getScaledInstance((t3 * iWidth) / iHeight, t3, Image.SCALE_SMOOTH); tumb4 = i.getScaledInstance((t4 * iWidth) / iHeight, t4, Image.SCALE_SMOOTH); //w = (t4 * iWidth) / iHeight; //h = t4; } tumb4 = estampar(tumb4); Util.log("Salvando Imagens"); save(tumb1, diretorio + File.separator + "_a" + arquivo); save(tumb2, diretorio + File.separator + "_b" + arquivo); save(tumb3, diretorio + File.separator + "_c" + arquivo); save(tumb4, diretorio + File.separator + "_d" + arquivo); } catch (Exception e) { Util.err.println("[Thumbnail.makeThumbs]/ERRO: Inesperado - " + e.getMessage()); e.printStackTrace(Util.err); } }