List of usage examples for java.io File canRead
public boolean canRead()
From source file:de.ingrid.interfaces.csw.tools.FileUtils.java
/** * This function will copy files or directories from one location to * another. note that the source and the destination must be mutually * exclusive. This function can not be used to copy a directory to a sub * directory of itself. The function will also have problems if the * destination files already exist./*from www .ja v a 2 s .com*/ * * @param src * -- A File object that represents the source for the copy * @param dest * -- A File object that represnts the destination for the copy. * @throws IOException * if unable to copy. * * Source: http://www.dreamincode.net/code/snippet1443.htm */ public static void copyRecursive(File src, File dest) throws IOException { // Check to ensure that the source is valid... if (!src.exists()) { throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + "."); } else if (!src.canRead()) { // check to ensure we have rights to the // source... throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + "."); } // is this a directory copy? if (src.isDirectory()) { if (!dest.exists()) { // does the destination already exist? // if not we need to make it exist if possible (note this is // mkdirs not mkdir) if (!dest.mkdirs()) { throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + "."); } } // get a listing of files... String list[] = src.list(); // copy all the files in the list. for (String element : list) { File dest1 = new File(dest, element); File src1 = new File(src, element); copyRecursive(src1, dest1); } } else { // This was not a directory, so lets just copy the file FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; // Buffer 4K at a time (you can // change this). int bytesRead; try { // open the files for input and output fin = new FileInputStream(src); fout = new FileOutputStream(dest); // while bytesRead indicates a successful read, lets write... while ((bytesRead = fin.read(buffer)) >= 0) { fout.write(buffer, 0, bytesRead); } fin.close(); fout.close(); fin = null; fout = null; } catch (IOException e) { // Error copying file... IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath() + "to" + dest.getAbsolutePath() + "."); wrapper.initCause(e); wrapper.setStackTrace(e.getStackTrace()); throw wrapper; } finally { // Ensure that the files are closed (if they were open). if (fin != null) { fin.close(); } if (fout != null) { fin.close(); } } } }
From source file:net.cloudkit.relaxation.VerifyImage.java
public static void convert(File source, String formatName, String result) { try {//from w w w . ja va 2 s .c o m // File f = new File(source); source.canRead(); BufferedImage src = ImageIO.read(source); ImageIO.write(src, formatName, new File(result)); } catch (Exception e) { e.printStackTrace(); } }
From source file:edu.stanford.muse.util.ThunderbirdUtils.java
/** returns a list of thunderbird accounts. each list is in turn a list of length exactly 4: account name, hostname, server type, user name */// www. jav a 2 s. c om public static List<List<String>> getThunderbirdAccounts() { try { List<List<String>> newResult = getThunderbirdAccountsNew(); if (newResult != null) return newResult; } catch (Exception e) { log.warn("unable to process thunderbird profile with new thunderbird parser"); Util.print_exception(e, log); } List<List<String>> result = new ArrayList<List<String>>(); try { String rootDir = ThunderbirdUtils.getThunderbirdProfileDir(); String prefs = rootDir + File.separator + "prefs.js"; File f = new File(prefs); if (!f.exists() || !f.canRead()) { EmailUtils.log.info("Thunderbird probably not installed: no prefs.js in directory: " + prefs); return result; } LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(prefs), "UTF-8")); // example fragment of input // user_pref("mail.server.server2.capability", 21520929); // user_pref("mail.server.server2.directory", "AAAAAAH0AAIAAQxNYWNpbnRvc2ggSEQAAAAAAAAAAAAAAAAAAADGqxmGSCsAAAAJi1ASeGVub24uc3RhbmZvcmQuZWR1AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmLUcbnohEAAAAAAAAAAP////8AAAkgAAAAAAAAAAAAAAAAAAAACEltYXBNYWlsABAACAAAxqt79gAAABEACAAAxugEgQAAAAEAHAAJi1AACYsXAAmLFQAJiw8AB/mpAAf5qAAAkOcAAgBjTWFjaW50b3NoIEhEOlVzZXJzOmhhbmdhbDpMaWJyYXJ5OlRodW5kZXJiaXJkOlByb2ZpbGVzOjcyeHZzMXd3LmRlZmF1bHQ6SW1hcE1haWw6eGVub24uc3RhbmZvcmQuZWR1AAAOACYAEgB4AGUAbgBvAG4ALgBzAHQAYQBuAGYAbwByAGQALgBlAGQAdQAPABoADABNAGEAYwBpAG4AdABvAHMAaAAgAEgARAASAFZVc2Vycy9oYW5nYWwvTGlicmFyeS9UaHVuZGVyYmlyZC9Qcm9maWxlcy83Mnh2czF3dy5kZWZhdWx0L0ltYXBNYWlsL3hlbm9uLnN0YW5mb3JkLmVkdQATAAEvAAAVAAIADf//AAA="); // user_pref("mail.server.server2.directory-rel", "[ProfD]ImapMail/xenon.stanford.edu"); // user_pref("mail.server.server2.download_on_biff", true); // user_pref("mail.server.server2.hostname", "xenon.stanford.edu"); // user_pref("mail.server.server2.login_at_startup", true); // user_pref("mail.server.server2.max_cached_connections", 5); // user_pref("mail.server.server2.name", "Stanford CS"); // user_pref("mail.server.server2.namespace.other_users", "\"~\""); // user_pref("mail.server.server2.namespace.personal", "\"#mh/\",\"#mhinbox\",\"\""); // user_pref("mail.server.server2.namespace.public", "\"#public/\",\"#news.\",\"#ftp/\",\"#shared/\""); // user_pref("mail.server.server2.timeout", 29); // user_pref("mail.server.server2.type", "imap"); // user_pref("mail.server.server2.userName", "hangal"); // be careful not to match a ...hostname line or a ...namespace line with the .name pattern // // that's why we need an explicit dot before and a quote after the type of field in the pattern // note: there are 2 fields: hostname and realhostname - realhostname has precedence if it exists // see: http://forums.mozillazine.org/viewtopic.php?f=39&t=1697195 Pattern accountNamePat = Pattern.compile(".*\"mail.server.server.*\\.name\".*"); Pattern hostnamePat = Pattern.compile(".*\"mail.server.server.*\\.hostname\".*"); Pattern realHostnamePat = Pattern.compile(".*\"mail.server.server.*\\.realhostname\".*"); Pattern serverTypePat = Pattern.compile(".*\"mail.server.server.*\\.type\".*"); Pattern usernamePat = Pattern.compile(".*\"mail.server.server.*\\.userName\".*"); Pattern userRealNamePat = Pattern.compile(".*\"mail.identity.id.*\\.fullName\".*"); Pattern userEmailPat = Pattern.compile(".*\"mail.identity.id.*\\.useremail\".*"); Pattern directoryRelPat = Pattern.compile(".*\"mail.server.server.*\\.directory-rel\".*"); Pattern fccFolderPat = Pattern.compile(".*\"mail.identity.id.*\\.fcc_folder\".*"); Map<String, String> accountNameMap = new LinkedHashMap<String, String>(); Map<String, String> hostnameMap = new LinkedHashMap<String, String>(); Map<String, String> realHostnameMap = new LinkedHashMap<String, String>(); Map<String, String> serverTypeMap = new LinkedHashMap<String, String>(); Map<String, String> usernameMap = new LinkedHashMap<String, String>(); Map<String, String> userEmailMap = new LinkedHashMap<String, String>(); Map<String, String> userRealNameMap = new LinkedHashMap<String, String>(); Map<String, String> directoryRelMap = new LinkedHashMap<String, String>(); Map<String, String> fccFolderMap = new LinkedHashMap<String, String>(); while (true) { String line = lnr.readLine(); if (line == null) { lnr.close(); break; } if (accountNamePat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server"); accountNameMap.put(pair.getFirst(), pair.getSecond()); } if (hostnamePat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server"); hostnameMap.put(pair.getFirst(), pair.getSecond()); } if (realHostnamePat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server"); realHostnameMap.put(pair.getFirst(), pair.getSecond()); } else if (serverTypePat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server"); String serverType = pair.getSecond(); if ("imap".equals(serverType)) serverType = "imaps"; if ("pop".equals(serverType)) serverType = "pops"; serverTypeMap.put(pair.getFirst(), serverType); } else if (usernamePat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server"); usernameMap.put(pair.getFirst(), pair.getSecond()); } else if (userEmailPat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "id"); userEmailMap.put(pair.getFirst(), pair.getSecond()); } else if (userRealNamePat.matcher(line).matches()) { Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "id"); userRealNameMap.put(pair.getFirst(), pair.getSecond()); } else if (directoryRelPat.matcher(line).matches()) { // for local folders the line is like user_pref("mail.server.server1.directory-rel", "[ProfD]../../../../../../tmp/tb"); // Convert [ProfD]../../../../../../tmp/tb to the correct path by replacing [ProfD] with the profile dir Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "server"); String directoryRel = pair.getSecond(); if (directoryRel != null) { if (directoryRel.startsWith("[ProfD]")) directoryRel = directoryRel.replace("[ProfD]", ThunderbirdUtils.getThunderbirdProfileDir() + File.separator); // we also have to correct the ../../ to \..\... for windows directoryRel = directoryRel.replaceAll("/", File.separator); directoryRelMap.put(pair.getFirst(), directoryRel); } } else if (fccFolderPat.matcher(line).matches()) { // the line looks like user_pref("mail.identity.id1.fcc_folder", "imap://hangal@xenon.stanford.edu/Sent"); Pair<String, String> pair = ThunderbirdUtils.parseLine(line, "id"); String fccFolderFull = pair.getSecond(); if (fccFolderFull != null) { // fccFolder imap://hangal@xenon.stanford.edu/Sent String fccFolder = fccFolderFull.replaceAll("[^/]*/+[^/]*/+(.*$)", "$1"); // skip the first 2 tokens, split by / if (!fccFolderFull.equals(fccFolder)) // only if not equal is it valid fccFolderMap.put(pair.getFirst(), fccFolder); } } } for (String key : serverTypeMap.keySet()) { String s = serverTypeMap.get(key).toLowerCase(); // we only know how to handle imap and pop and local folders // other things like smart folders, don't list. if (!s.startsWith("imap") && !s.startsWith("pop") && !"Local Folders".equals(accountNameMap.get(key))) continue; List<String> params = new ArrayList<String>(); params.add(accountNameMap.get(key)); String hostnameToUse = realHostnameMap.get(key); if (hostnameToUse == null) hostnameToUse = hostnameMap.get(key); params.add(hostnameToUse); params.add(serverTypeMap.get(key)); params.add(usernameMap.get(key)); params.add(userEmailMap.get(key)); params.add(userRealNameMap.get(key)); params.add(directoryRelMap.get(key)); params.add(fccFolderMap.get(key)); String str = "Tbird accountname=\"" + accountNameMap.get(key) + "\" " + "hostname=\"" + hostnameMap.get(key) + "\" " + "serverType=\"" + serverTypeMap.get(key) + "\" " + "username=\"" + usernameMap.get(key) + "\" " + "userEmail=\"" + userEmailMap.get(key) + "\" " + "userRealName=\"" + userRealNameMap.get(key) + "\" " + "directoryRel=\"" + directoryRelMap.get(key) + "\"" + "fccFolder=\"" + fccFolderMap.get(key) + "\""; EmailUtils.log.debug(str); // System.out.println(str); result.add(params); } lnr.close(); } catch (Exception e) { System.err.println("REAL WARNING: exception trying to read thunderbird prefs" + Util.stackTrace(e)); } return Collections.unmodifiableList(result); }
From source file:com.openkm.servlet.RepositoryStartupServlet.java
/** * Start OpenKM and possible repository and database initialization *//*from w w w. j ava 2 s .co m*/ public static synchronized void start() throws ServletException { SystemAuthentication systemAuth = new SystemAuthentication(); if (running) { throw new IllegalStateException("OpenKM already started"); } try { log.info("*** Repository initializing... ***"); if (Config.REPOSITORY_NATIVE) { systemAuth.enable(); DbRepositoryModule.initialize(); systemAuth.disable(); } else { JcrRepositoryModule.initialize(); } log.info("*** Repository initialized ***"); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } log.info("*** User database initialized ***"); if (!Config.REPOSITORY_NATIVE) { // Test for datastore SessionImpl si = (SessionImpl) JcrRepositoryModule.getSystemSession(); if (((RepositoryImpl) si.getRepository()).getDataStore() == null) { hasConfiguredDataStore = false; } else { hasConfiguredDataStore = true; } } // Create timers uiTimer = new Timer("Update Info", true); cronTimer = new Timer("Crontab Manager", true); uinTimer = new Timer("User Interface Notification", true); // Workflow log.info("*** Initializing workflow engine... ***"); JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext(); jbpmContext.setSessionFactory(HibernateUtil.getSessionFactory()); jbpmContext.getGraphSession(); jbpmContext.getJbpmConfiguration().getJobExecutor().start(); // startJobExecutor(); jbpmContext.close(); // Mime types log.info("*** Initializing MIME types... ***"); MimeTypeConfig.loadMimeTypes(); log.info("*** Activating update info ***"); ui = new UpdateInfo(); uiTimer.schedule(ui, TimeUnit.MINUTES.toMillis(5), TimeUnit.HOURS.toMillis(24)); // First in 5 min, next each 24 hours log.info("*** Activating cron ***"); cron = new Cron(); Calendar calCron = Calendar.getInstance(); calCron.add(Calendar.MINUTE, 1); calCron.set(Calendar.SECOND, 0); calCron.set(Calendar.MILLISECOND, 0); // Round begin to next minute, 0 seconds, 0 miliseconds cronTimer.scheduleAtFixedRate(cron, calCron.getTime(), 60 * 1000); // First in 1 min, next each 1 min log.info("*** Activating UI Notification ***"); uin = new UINotification(); // First in 1 second next in x minutes uinTimer.scheduleAtFixedRate(uin, 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_UI_NOTIFICATION)); try { // General maintenance works String dapContent = "com.openkm.dao.DashboardActivityDAO.purge();"; CronTabUtils.createOrUpdate("Dashboard Activity Purge", "@daily", dapContent); String uisContent = "com.openkm.cache.UserItemsManager.serialize();"; CronTabUtils.createOrUpdate("User Items Serialize", "@hourly", uisContent); String ruiContent = "com.openkm.cache.UserItemsManager.refreshDbUserItems();"; CronTabUtils.createOrUpdate("Refresh User Items", "@weekly", ruiContent); String umiContent = "new com.openkm.core.UserMailImporter().run();"; CronTabUtils.createOrUpdate("User Mail Importer", "*/30 * * * *", umiContent); String tewContent = "new com.openkm.extractor.TextExtractorWorker().run();"; CronTabUtils.createOrUpdate("Text Extractor Worker", "*/5 * * * *", tewContent); String swdContent = "new com.openkm.core.Watchdog().run();"; CronTabUtils.createOrUpdate("Session Watchdog", "*/5 * * * *", swdContent); String pptContent = "new com.openkm.util.pendtask.PendingTaskExecutor().run();"; CronTabUtils.createOrUpdate("Process Pending Tasks", "*/5 * * * *", pptContent); // Datastore garbage collection if (!Config.REPOSITORY_NATIVE && hasConfiguredDataStore) { String dgcContent = "new com.openkm.module.jcr.stuff.DataStoreGarbageCollector().run();"; CronTabUtils.createOrUpdate("Datastore Garbage Collector", "@daily", dgcContent); } } catch (Exception e) { log.warn(e.getMessage(), e); } try { log.info("*** Activating thesaurus repository ***"); RDFREpository.getInstance(); } catch (Exception e) { log.warn(e.getMessage(), e); } try { if (Config.REMOTE_CONVERSION_SERVER.equals("")) { if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) { log.info("*** Start OpenOffice manager ***"); DocConverter.getInstance().start(); } else if (!Config.SYSTEM_OPENOFFICE_SERVER.equals("")) { log.info("*** Using OpenOffice conversion server ***"); } else { log.warn("*** No OpenOffice manager nor server configured ***"); } } else { log.info("*** Remote conversion configured ***"); } } catch (Throwable e) { log.warn(e.getMessage(), e); } // Initialize plugin framework ExtensionManager.getInstance(); try { log.info("*** Execute start script ***"); File script = new File(Config.HOME_DIR + File.separatorChar + Config.START_SCRIPT); ExecutionUtils.runScript(script); File jar = new File(Config.HOME_DIR + File.separatorChar + Config.START_JAR); ExecutionUtils.getInstance().runJar(jar); } catch (Throwable e) { log.warn(e.getMessage(), e); } try { log.info("*** Execute start SQL ***"); File sql = new File(Config.HOME_DIR + File.separatorChar + Config.START_SQL); if (sql.exists() && sql.canRead()) { FileReader fr = new FileReader(sql); HibernateUtil.executeSentences(fr); IOUtils.closeQuietly(fr); } else { log.warn("Unable to read sql: {}", sql.getPath()); } } catch (Throwable e) { log.warn(e.getMessage(), e); } // OpenKM is started running = true; }
From source file:gov.nih.cadsr.transform.FilesTransformation.java
public static String transformFormToCSV(String xmlFile) { StringBuffer sb = null;//from w ww .ja v a 2 s. c o m try { File tf = new File("/local/content/cadsrapi/transform/xslt/", "formbuilder.xslt"); // template file String path = "/local/content/cadsrapi/transform/data/"; String ext = "txt"; File dir = new File(path); String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext); File rf = new File(dir, name); if (tf == null || !tf.exists() || !tf.canRead()) { System.out.println("File path incorrect"); return ""; } long startTime = System.currentTimeMillis(); //Obtain a new instance of a TransformerFactory. TransformerFactory f = TransformerFactory.newInstance(); // Process the Source into a Transformer Object...Construct a StreamSource from a File. Transformer t = f.newTransformer(new StreamSource(tf)); //Construct a StreamSource from input and output Source s; try { s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8")))); Result r = new StreamResult(rf); //Transform the XML Source to a Result. t.transform(s, r); System.out.println("Tranformation completed ..."); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block System.out.println(e1.toString()); } //convert output file to string try { BufferedReader bf = new BufferedReader(new FileReader(rf)); sb = new StringBuffer(); try { String currentLine; while ((currentLine = bf.readLine()) != null) { sb.append(currentLine).append("\n"); //System.out.println(bf.readLine()); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("Transformation took " + (endTime - startTime) + " milliseconds"); System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds"); } catch (TransformerConfigurationException e) { System.out.println(e.toString()); } catch (TransformerException e) { System.out.println(e.toString()); } return sb.toString(); }
From source file:edu.internet2.middleware.shibboleth.common.attribute.AttributeAuthorityCLI.java
/** * Loads the configuration files into a Spring application context. * /*w w w .j a va 2 s . c o m*/ * @param configDir directory containing spring configuration files * @param springExts colon-separated list of spring extension files * * @return loaded application context * * @throws java.io.IOException throw if there is an error loading the configuration files * @throws ResourceException if there is an error loading the configuration files */ private static ApplicationContext loadConfigurations(String configDir, String springExts) throws IOException, ResourceException { File configDirectory; if (configDir != null) { configDirectory = new File(configDir); } else { configDirectory = new File(System.getenv("IDP_HOME") + "/conf"); } if (!configDirectory.exists() || !configDirectory.isDirectory() || !configDirectory.canRead()) { errorAndExit("Configuration directory " + configDir + " does not exist, is not a directory, or is not readable", null); } loadLoggingConfiguration(configDirectory.getAbsolutePath()); File config; List<String> configFiles = new ArrayList<String>(); List<Resource> configs = new ArrayList<Resource>(); // Add built-in files. for (String i : aacliConfigs) { configFiles.add(i); } // Add extensions, if any. if (springExts != null && !springExts.isEmpty()) { String[] extFiles = springExts.split(":"); for (String extFile : extFiles) { configFiles.add(extFile); } } for (String cfile : configFiles) { config = new File(configDirectory.getPath() + File.separator + cfile); if (config.isDirectory() || !config.canRead()) { errorAndExit( "Configuration file " + config.getAbsolutePath() + " is a directory or is not readable", null); } configs.add(new FilesystemResource(config.getPath())); } GenericApplicationContext gContext = new GenericApplicationContext(); SpringConfigurationUtils.populateRegistry(gContext, configs); gContext.refresh(); return gContext; }
From source file:gov.nih.cadsr.transform.FilesTransformation.java
public static String transformCdeToCSV(String xmlFile) { StringBuffer sb = null;//w w w . j a v a 2 s . co m try { File tf = new File("/local/content/cadsrapi/transform/xslt/", "cdebrowser.xslt"); // template file String path = "/local/content/cadsrapi/transform/data/"; String ext = "txt"; File dir = new File(path); String name = String.format("%s.%s", RandomStringUtils.randomAlphanumeric(8), ext); File rf = new File(dir, name); if (tf == null || !tf.exists() || !tf.canRead()) { System.out.println("File path incorrect"); return ""; } long startTime = System.currentTimeMillis(); //Obtain a new instance of a TransformerFactory. TransformerFactory f = TransformerFactory.newInstance(); // Process the Source into a Transformer Object...Construct a StreamSource from a File. Transformer t = f.newTransformer(new StreamSource(tf)); /* Source s = new StreamSource(xmlFile); Result r = new StreamResult(rf); //Transform the XML Source to a Result. t.transform(s,r); System.out.println("Tranformation completed ..."); */ //Construct a StreamSource from input and output Source s; try { s = new StreamSource((new ByteArrayInputStream(xmlFile.getBytes("utf-8")))); Result r = new StreamResult(rf); //Transform the XML Source to a Result. t.transform(s, r); System.out.println("Tranformation completed ..."); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block System.out.println(e1.toString()); } try { BufferedReader bf = new BufferedReader(new FileReader(rf)); sb = new StringBuffer(); try { String currentLine; while ((currentLine = bf.readLine()) != null) { sb.append(currentLine).append("\n"); //System.out.println(bf.readLine()); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("Transformation took " + (endTime - startTime) + " milliseconds"); System.out.println("Transformation took " + (endTime - startTime) / 1000 + " seconds"); } catch (TransformerConfigurationException e) { System.out.println(e.toString()); e.printStackTrace(); } catch (TransformerException e) { System.out.println(e.toString()); } return sb.toString(); }
From source file:com.taobao.android.builder.tools.bundleinfo.BundleInfoUtils.java
private static Map<String, BundleInfo> getBundleInfoMap(AppVariantContext appVariantContext) throws IOException { File baseBunfleInfoFile = new File( appVariantContext.getScope().getGlobalScope().getProject().getProjectDir(), "bundleBaseInfoFile.json"); //??//from w w w. j av a 2 s . c o m Map<String, BundleInfo> bundleFileMap = Maps.newHashMap(); if (null != baseBunfleInfoFile && baseBunfleInfoFile.exists() && baseBunfleInfoFile.canRead()) { String bundleBaseInfo = FileUtils.readFileToString(baseBunfleInfoFile, "utf-8"); bundleFileMap = JSON.parseObject(bundleBaseInfo, new TypeReference<Map<String, BundleInfo>>() { }); } List<AwbBundle> awbBundles = AtlasBuildContext.androidDependencyTrees .get(appVariantContext.getVariantData().getName()).getAwbBundles(); List<String> duplicatedBundleInfo = new ArrayList<>(); for (AwbBundle awbBundle : awbBundles) { String name = awbBundle.getResolvedCoordinates().getArtifactId(); File bundleBaseInfoFile = new File(awbBundle.getAndroidLibrary().getFolder(), "bundleBaseInfoFile.json"); if (bundleBaseInfoFile.exists()) { String json = FileUtils.readFileToString(bundleBaseInfoFile, "utf-8"); BundleInfo bundleInfo = JSON.parseObject(json, BundleInfo.class); if (bundleFileMap.containsKey(name)) { appVariantContext.getProject().getLogger() .error("bundleBaseInfoFile>>>" + name + " has declared bundleBaseInfoFile"); duplicatedBundleInfo.add(name); } bundleFileMap.put(name, bundleInfo); } } if (duplicatedBundleInfo.size() > 0) { FileUtils.writeLines(new File(appVariantContext.getProject().getBuildDir(), "outputs/warning-dupbundleinfo.properties"), duplicatedBundleInfo); } return bundleFileMap; }
From source file:jBittorrentAPI.utils.IOManager.java
/** * Read all available bytes from the given file * @param file File/*from w ww . j a v a 2 s . c om*/ * @return byte[] */ public static byte[] readBytesFromFile(File file) { long file_size_long = -1; byte[] file_bytes = null; InputStream file_stream; try { file_stream = new FileInputStream(file); if (!file.exists()) { System.err.println("Error: [TorrentFileHandler.java] The file \"" + file.getName() + "\" does not exist. Please make sure you have the correct path to the file."); return null; } if (!file.canRead()) { System.err.println("Error: [TorrentFileHandler.java] Cannot decode from \"" + file.getName() + "\". Please make sure the file permissions are set correctly."); return null; } file_size_long = file.length(); if (file_size_long > Integer.MAX_VALUE) { System.err.println("Error: [TorrentFileHandler.java] The file \"" + file.getName() + "\" is too large to be decode by this class."); return null; } file_bytes = new byte[(int) file_size_long]; int file_offset = 0; int bytes_read = 0; while (file_offset < file_bytes.length && (bytes_read = file_stream.read(file_bytes, file_offset, file_bytes.length - file_offset)) >= 0) { file_offset += bytes_read; } if (file_offset < file_bytes.length) { throw new IOException("Could not completely decode file \"" + file.getName() + "\"."); } file_stream.close(); } catch (FileNotFoundException e) { System.err.println("Error: [TorrentFileHandler.java] The file \"" + file.getName() + "\" does not exist. Please make sure you have the correct path to the file."); return null; } catch (IOException e) { System.err.println( "Error: [TorrentFileHandler.java] There was a general, unrecoverable I/O error while reading from \"" + file.getName() + "\"."); System.err.println(e.getMessage()); } return file_bytes; }
From source file:morphy.utils.FileUtils.java
/** * This code was obtained from:// w ww. j a v a 2 s . co m * http://www.dreamincode.net/code/snippet1443.htm * * This function will copy files or directories from one location to * another. note that the source and the destination must be mutually * exclusive. This function can not be used to copy a directory to a sub * directory of itself. The function will also have problems if the * destination files already exist. * * @param src * -- A File object that represents the source for the copy * @param dest * -- A File object that represents the destination for the copy. * @throws IOException * if unable to copy. */ public static void copyFiles(File src, File dest) throws IOException { if (src.getName().startsWith(".")) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring " + src.getAbsolutePath() + " because name started with ."); } return; } // Check to ensure that the source is valid... if (!src.exists()) { throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + "."); } else if (!src.canRead()) { // check to ensure we have rights to the // source... throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + "."); } // is this a directory copy? if (src.isDirectory()) { if (!dest.exists()) { // does the destination already exist? // if not we need to make it exist if possible (note this is // mkdirs not mkdir) if (!dest.mkdirs()) { throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + "."); } if (LOG.isDebugEnabled()) { LOG.debug("Created directory " + dest.getAbsolutePath()); } } // get a listing of files... String list[] = src.list(); // copy all the files in the list. for (String element : list) { File dest1 = new File(dest, element); File src1 = new File(src, element); copyFiles(src1, dest1); } } else { // This was not a directory, so lets just copy the file FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; // Buffer 4K at a time (you can // change this). int bytesRead; try { // open the files for input and output fin = new FileInputStream(src); fout = new FileOutputStream(dest); // while bytesRead indicates a successful read, lets write... while ((bytesRead = fin.read(buffer)) >= 0) { fout.write(buffer, 0, bytesRead); } if (LOG.isDebugEnabled()) { LOG.debug("Copied " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); } } catch (IOException e) { // Error copying file... IOException wrapper = new IOException("copyFiles: Unable to copy file: " + src.getAbsolutePath() + "to" + dest.getAbsolutePath() + "."); wrapper.initCause(e); wrapper.setStackTrace(e.getStackTrace()); throw wrapper; } finally { // Ensure that the files are closed (if they were open). if (fin != null) { try { fin.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } } }