List of usage examples for java.io File equals
public boolean equals(Object obj)
From source file:edu.cornell.mannlib.vitro.webapp.filestorage.backend.FileStorageImpl.java
/** * We have deleted this file. If the parent directory is now empty, delete * it. Then check its parent in turn. This continues until we find a parent * that we will not delete, either because it is not empty, or because it is * the file storage root.//from www. j av a 2s .co m */ private void deleteEmptyParents(File file) { File parent = file.getParentFile(); if (parent == null) { log.warn("This is crazy. How can file '" + file.getAbsolutePath() + "' have no parent?"); return; } if (parent.equals(rootDir)) { log.trace("Not deleting the root directory."); return; } File[] children = parent.listFiles(); if (children == null) { log.warn("This is crazy. How can file '" + parent.getAbsolutePath() + "' not be a directory?"); return; } if (children.length > 0) { log.trace("Directory '" + parent.getAbsolutePath() + "' is not empty. Not deleting."); return; } log.trace("Deleting empty directory '" + parent.getAbsolutePath() + "'"); parent.delete(); if (parent.exists()) { log.warn("Failed to delete directory '" + parent.getAbsolutePath() + "'"); return; } deleteEmptyParents(parent); }
From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java
private void processPictureWhenReady(final String picturePath) { final File pictureFile = new File(picturePath); //Map<String, String > result = new HashMap<String,String>(); if (pictureFile.exists()) { // The picture is ready; process it. Bitmap imageBitmap = null;//from w w w . ja va 2 s . co m try { // Bundle extras = data.getExtras(); // imageBitmap = (Bitmap) extras.get("data"); FileInputStream fis = new FileInputStream(picturePath); //get the bitmap from file imageBitmap = (Bitmap) BitmapFactory.decodeStream(fis); if (imageBitmap != null) { Bitmap lScaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 1600, 1200, false); if (lScaledBitmap != null) { imageBitmap.recycle(); imageBitmap = null; ByteArrayOutputStream lImageBytes = new ByteArrayOutputStream(); lScaledBitmap.compress(Bitmap.CompressFormat.JPEG, 30, lImageBytes); lScaledBitmap.recycle(); lScaledBitmap = null; byte[] lImageByteArray = lImageBytes.toByteArray(); HashMap<String, String> lValuePairs = new HashMap<String, String>(); lValuePairs.put("base64Image", Base64.encodeToString(lImageByteArray, Base64.DEFAULT)); lValuePairs.put("compressionLevel", "30"); lValuePairs.put("documentIdentifier", "DRIVER_LICENSE_CA"); lValuePairs.put("documentHints", ""); lValuePairs.put("dataReturnLevel", "15"); lValuePairs.put("returnImageType", "1"); lValuePairs.put("rotateImage", "0"); lValuePairs.put("data1", ""); lValuePairs.put("data2", ""); lValuePairs.put("data3", ""); lValuePairs.put("data4", ""); lValuePairs.put("data5", ""); lValuePairs.put("userName", "zbroyan@miteksystems.com"); lValuePairs.put("password", "google1"); lValuePairs.put("phoneKey", "1"); lValuePairs.put("orgName", "MobileImagingOrg"); String lSoapMsg = formatSOAPMessage("InsertPhoneTransaction", lValuePairs); DefaultHttpClient mHttpClient = new DefaultHttpClient(); // mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.R) HttpPost mHttpPost = new HttpPost(); mHttpPost.setHeader("User-Agent", "UCSD Team"); mHttpPost.setHeader("Content-typURIe", "text/xml;charset=UTF-8"); //mHttpPost.setURI(URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx?op=InsertPhoneTransaction")); mHttpPost.setURI( URI.create("https://mi1.miteksystems.com/mobileimaging/ImagingPhoneService.asmx")); StringEntity se = new StringEntity(lSoapMsg, HTTP.UTF_8); se.setContentType("text/xml; charset=UTF-8"); mHttpPost.setEntity(se); HttpResponse mResponse = mHttpClient.execute(mHttpPost, new BasicHttpContext()); String responseString = new BasicResponseHandler().handleResponse(mResponse); parseXML(responseString); //Todo: this is test code. Need to be implemented //result = parseXML(testStr); Log.i("test", "test:" + " " + responseString); Log.i("test", "test: " + " " + map.size()); } } } catch (Exception e) { e.printStackTrace(); } // this part will be relocated in order to let the the server process picture if (map.size() == 0) { Intent display = new Intent(getApplicationContext(), DisplayInfoFailed.class); display.putExtra("result", (java.io.Serializable) iQAMsg); startActivity(display); } else { Intent display = new Intent(getApplicationContext(), DisplayInfo.class); display.putExtra("result", (java.io.Serializable) map); startActivity(display); } } else { // The file does not exist yet. Before starting the file observer, you // can update your UI to let the user know that the application is // waiting for the picture (for example, by displaying the thumbnail // image and a progress indicator). final File parentDirectory = pictureFile.getParentFile(); FileObserver observer = new FileObserver(parentDirectory.getPath(), FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) { // Protect against additional pending events after CLOSE_WRITE // or MOVED_TO is handled. private boolean isFileWritten; @Override public void onEvent(int event, final String path) { if (!isFileWritten) { // For safety, make sure that the file that was created in // the directory is actually the one that we're expecting. File affectedFile = new File(parentDirectory, path); isFileWritten = affectedFile.equals(pictureFile); if (isFileWritten) { stopWatching(); // Now that the file is ready, recursively call // processPictureWhenReady again (on the UI thread). runOnUiThread(new Runnable() { @Override public void run() { new LongOperation().execute(picturePath); } }); } } } }; observer.startWatching(); } }
From source file:edu.kit.dama.ui.simon.util.SimonConfigurator.java
public void setConfigLocation(File pPath) throws ConfigurationException { if (pPath == null) { throw new IllegalArgumentException("Argument pPath must not be null"); }// ww w . j av a2 s . c o m if (!pPath.exists() || !pPath.isDirectory()) { throw new ConfigurationException("Argument pPath must be an existing directory"); } if (!pPath.equals(configPath)) { LOGGER.debug("Reloading configuration"); configPath = pPath; probes.clear(); configs.clear(); configure(); } else { LOGGER.debug("New config file is equal to current config file. Skipping reconfiguration."); } if (observer != null) { LOGGER.debug("Stopping directory observer"); try { LOGGER.debug(" - Removing observer from monitor"); configMontitor.removeObserver(observer); LOGGER.debug(" - Destroying observer"); observer.destroy(); } catch (Exception e) { LOGGER.info("Failed to stop observer, ignoring this.", e); } observer = null; } LOGGER.debug("Setting up directory observer for current configuration path {}", pPath); observer = new FileAlterationObserver(pPath); try { LOGGER.debug(" - Initializing directory observer"); observer.initialize(); LOGGER.debug(" - Directory observer successfully initialized. Adding listener."); observer.addListener(this); configMontitor.addObserver(observer); } catch (Exception e) { LOGGER.info("Failed to initialize directory observer. Configuration changes won't be tracked.", e); observer = null; } }
From source file:br.com.renatoccosta.regexrenamer.Renamer.java
public void setRootFolder(File rootFolder) throws RenamerException { if (rootFolder.equals(this.rootFolder)) { return;/*from w w w. j av a 2 s . c om*/ } if (!rootFolder.exists()) { throw new RenamerException(Messages.getFileNotFoundMessage()); } this.rootFolder = rootFolder; fillFileLists(); this.dirty = true; }
From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java
public Plugin loadPlugin(File file) throws InvalidPluginException { Validate.notNull(file, "File cannot be null"); if (!file.exists()) { throw new InvalidPluginException(new FileNotFoundException(file.getPath() + " does not exist")); }// w w w . ja v a2 s . c o m PluginDescriptionFile description; try { description = getPluginDescription(file); } catch (InvalidDescriptionException ex) { throw new InvalidPluginException(ex); } File dataFolder = new File(file.getParentFile(), description.getName()); File oldDataFolder = getDataFolder(file); // Found old data folder if (dataFolder.equals(oldDataFolder)) { // They are equal -- nothing needs to be done! } else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) { PluginManager.getLogger().log(Level.INFO, String.format("While loading %s (%s) found old-data folder: %s next to the new one: %s", description.getName(), file, oldDataFolder, dataFolder)); } else if (oldDataFolder.isDirectory() && !dataFolder.exists()) { if (!oldDataFolder.renameTo(dataFolder)) { throw new InvalidPluginException( "Unable to rename old data folder: '" + oldDataFolder + "' to: '" + dataFolder + "'"); } PluginManager.getLogger().log(Level.INFO, String.format("While loading %s (%s) renamed data folder: '%s' to '%s'", description.getName(), file, oldDataFolder, dataFolder)); } if (dataFolder.exists() && !dataFolder.isDirectory()) { throw new InvalidPluginException( String.format("Projected datafolder: '%s' for %s (%s) exists and is not a directory", dataFolder, description.getName(), file)); } List<String> depend = description.getDepend(); if (depend == null) { depend = ImmutableList.<String>of(); } for (String pluginName : depend) { if (loaders == null) { throw new UnknownDependencyException(pluginName); } PluginClassLoader current = loaders.get(pluginName); if (current == null) { throw new UnknownDependencyException(pluginName); } } PluginClassLoader loader; try { loader = new PluginClassLoader(this, getClass().getClassLoader(), description, dataFolder, file); } catch (InvalidPluginException ex) { throw ex; } catch (Throwable ex) { throw new InvalidPluginException(ex); } loaders.put(description.getName(), loader); return loader.plugin; }
From source file:org.jimcat.model.Image.java
/** * /*from w w w . ja v a2 s . c o m*/ * The equals method of Image checks wheter the absolute file of two images * is equal to determine if two images are equal. So it uses the equals * method of the absolute files derived from the file object stored in the * metadata of the images. This is because there should only be one image * with a given absolute path in the database. If any of the needed * parameters is null in this or the other Image this method delegetes the * equals to the equals in the superclass. * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (!(obj instanceof Image)) { return false; } Image other = (Image) obj; if (this.getMetadata() == null || other.getMetadata() == null) { return super.equals(other); } if (this.getMetadata().getPath() == null || other.getMetadata().getPath() == null) { return super.equals(other); } File thisPath = this.getMetadata().getPath().getAbsoluteFile(); File otherPath = other.getMetadata().getPath().getAbsoluteFile(); return thisPath.equals(otherPath); }
From source file:com.depas.utils.FileUtils.java
public static String extractPathRelativeToDirectory(File chrootIn, File absolutePathIn) { if (chrootIn == null || absolutePathIn == null) { throw new IllegalArgumentException("The arguments must be non-null."); }//from ww w .j av a2s. c o m File chroot = chrootIn; File absolutePath = absolutePathIn; // Canonization will turn things like "/home/dpa/dir/../dir" into "/home/dpa/dir". try { chroot = chroot.getCanonicalFile(); } catch (Exception ex) { logger.warn("Failed to obtain canonical form of the 'chroot' file [" + chroot.toString() + "].", ex); } try { absolutePath = absolutePath.getCanonicalFile(); } catch (Exception ex) { logger.warn( "Failed to obtain canonical form of the 'absolutePath' file [" + absolutePath.toString() + "].", ex); } String result = ""; String delim = ""; // safety limit of 200 iterations in case there is a loop in the file system for (int i = 0; i < 200 && absolutePath.getParentFile() != null; i++) { if (chroot.equals(absolutePath)) { return !result.isEmpty() ? result : "."; } result = absolutePath.getName() + delim + result; delim = "/"; absolutePath = absolutePath.getParentFile(); } // could not find a match return null; }
From source file:org.brandroid.openmanager.util.FileManager.java
/** * //from w ww. j a v a 2s .c o m * @param old the file to be copied * @param newDir the directory to move the file to * @return */ public int copyToDirectory(String old, String newDir) { final File old_file = new File(old); final File temp_dir = new File(newDir); final byte[] data = new byte[BUFFER]; int read = 0; if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) { String file_name = old.substring(old.lastIndexOf("/"), old.length()); File cp_file = new File(newDir + file_name); if (cp_file.equals(old_file)) return 0; try { BufferedInputStream i_stream = new BufferedInputStream(new FileInputStream(old_file)); BufferedOutputStream o_stream = new BufferedOutputStream(new FileOutputStream(cp_file)); while ((read = i_stream.read(data, 0, BUFFER)) != -1) o_stream.write(data, 0, read); o_stream.flush(); i_stream.close(); o_stream.close(); } catch (FileNotFoundException e) { Log.e("FileNotFoundException", e.getMessage()); return -1; } catch (IOException e) { Log.e("IOException", e.getMessage()); return -1; } } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) { String files[] = old_file.list(); String dir = newDir + old.substring(old.lastIndexOf("/"), old.length()); int len = files.length; if (!new File(dir).mkdir()) return -1; for (int i = 0; i < len; i++) copyToDirectory(old + "/" + files[i], dir); } else if (!temp_dir.canWrite()) return -1; return 0; }
From source file:net.sf.mcf2pdf.mcfelements.FotobookBuilder.java
/** * Reads the given MCF input file and creates an MCF DOM reflecting the * relevant parts of the content.//from w ww. j a v a 2 s .co m * * @param file MCF input file. * * @return A Fotobook object reflecting the contents of the file. * * @throws IOException If any I/O related problem occurs reading the file. * @throws SAXException If any XML related problem occurs reading the file. */ public McfFotobook readFotobook(File file) throws IOException, SAXException { Digester digester = new Digester(); configurator.configureDigester(digester, file); McfFotobook fb = digester.parse(file); // try to set file on it try { BeanUtils.setProperty(fb, "file", file); } catch (Exception e) { // ignore - digester configurator will (hopefully) do it anyhow } // if this is thrown, your McfFotobook implementation has no setFile(), // and your configurator has also not set it. if (!file.equals(fb.getFile())) throw new IllegalStateException( "File could not be set on photobook. Please check used DigesterConfigurator."); return fb; }
From source file:org.bsc.maven.plugin.findclass.ClasspathDescriptor.java
private void addDirectory(final File element, final String parentPackageName, final File directory) { if (addCached(element)) { return;//from w w w . ja va 2 s .co m } final List<String> classes = new ArrayList<>(); final List<String> resources = new ArrayList<>(); final File[] files = directory.listFiles(); final String pckgName = element.equals(directory) ? null : (parentPackageName == null ? "" : parentPackageName + ".") + directory.getName(); if (files != null && files.length > 0) { for (File file : files) { if (file.isDirectory() && !IGNORED_LOCAL_DIRECTORIES.contains(file.getName().toUpperCase())) { addDirectory(element, pckgName, file); } else if (file.isFile()) { if ("class".equals(FilenameUtils.getExtension(file.getName()))) { final String className = (pckgName == null ? "" : pckgName + ".") + FilenameUtils.getBaseName(file.getName()); classes.add(className); addClass(className, element); } else { final String resourcePath = (pckgName == null ? "" : pckgName.replace('.', '/') + "/") + file.getName(); resources.add(resourcePath); addResource(resourcePath, element); } } } } CACHED_BY_ELEMENT.put(element, new Cached(classes, resources)); }