private void validate( File file, Collection<Exception> exceptions, Collection<MavenProjectProblem> problems, Collection<MavenId> unresolvedArtifacts) throws RemoteException { for (Exception each : exceptions) { Maven3ServerGlobals.getLogger().info(each); if (each instanceof InvalidProjectModelException) { ModelValidationResult modelValidationResult = ((InvalidProjectModelException) each).getValidationResult(); if (modelValidationResult != null) { for (Object eachValidationProblem : modelValidationResult.getMessages()) { problems.add( MavenProjectProblem.createStructureProblem( file.getPath(), (String) eachValidationProblem)); } } else { problems.add( MavenProjectProblem.createStructureProblem( file.getPath(), each.getCause().getMessage())); } } else if (each instanceof ProjectBuildingException) { String causeMessage = each.getCause() != null ? each.getCause().getMessage() : each.getMessage(); problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), causeMessage)); } else { problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getMessage())); } } unresolvedArtifacts.addAll(retrieveUnresolvedArtifactIds()); }
/** * Load a system library from a stream. Copies the library to a temp file and loads from there. * * @param libname name of the library (just used in constructing the library name) * @param is InputStream pointing to the library */ private void loadLibraryFromStream(String libname, InputStream is) { try { File tempfile = createTempFile(libname); OutputStream os = new FileOutputStream(tempfile); logger.debug("tempfile.getPath() = " + tempfile.getPath()); long savedTime = System.currentTimeMillis(); // Leo says 8k block size is STANDARD ;) byte buf[] = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); InputStream lock = new FileInputStream(tempfile); os.close(); double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3; logger.debug("Copying took " + seconds + " seconds."); logger.debug("Loading library from " + tempfile.getPath() + "."); System.load(tempfile.getPath()); lock.close(); } catch (IOException io) { logger.error("Could not create the temp file: " + io.toString() + ".\n"); } catch (UnsatisfiedLinkError ule) { logger.error("Couldn't load copied link file: " + ule.toString() + ".\n"); throw ule; } }
@Test public void open_ignores_rollback() { File f = TT.tempDbFile(); WriteAheadLog wal = new WriteAheadLog(f.getPath()); wal.walPutLong(1L, 11L); wal.commit(); wal.walPutLong(2L, 33L); wal.rollback(); wal.walPutLong(3L, 33L); wal.commit(); wal.seal(); wal.close(); wal = new WriteAheadLog(f.getPath()); wal.open( new WALSequence( new Object[] {WALSequence.beforeReplayStart}, new Object[] {WALSequence.writeLong, 1L, 11L}, new Object[] {WALSequence.commit}, // 2L is ignored, rollback section is skipped on hard replay new Object[] {WALSequence.writeLong, 3L, 33L}, new Object[] {WALSequence.commit})); wal.destroyWalFiles(); wal.close(); f.delete(); }
@Override public void updateFile(long companyId, long repositoryId, String fileName, String newFileName) throws DuplicateFileException, NoSuchFileException { if (fileName.equals(newFileName)) { throw new DuplicateFileException(companyId, repositoryId, newFileName); } File fileNameDir = getFileNameDir(companyId, repositoryId, fileName); if (!fileNameDir.exists()) { throw new NoSuchFileException(companyId, repositoryId, fileName); } File newFileNameDir = getFileNameDir(companyId, repositoryId, newFileName); if (newFileNameDir.exists()) { throw new DuplicateFileException(companyId, repositoryId, newFileName); } File parentFile = fileNameDir.getParentFile(); boolean renamed = FileUtil.move(fileNameDir, newFileNameDir); if (!renamed) { throw new SystemException( "File name directory was not renamed from " + fileNameDir.getPath() + " to " + newFileNameDir.getPath()); } deleteEmptyAncestors(companyId, repositoryId, parentFile); }
public static void copyDir( @NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter) throws IOException { ensureExists(toDir); if (isAncestor(fromDir, toDir, true)) { LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself."); return; } File[] files = fromDir.listFiles(); if (files == null) throw new IOException( CommonBundle.message("exception.directory.is.invalid", fromDir.getPath())); if (!fromDir.canRead()) throw new IOException( CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath())); for (File file : files) { if (filter != null && !filter.accept(file)) { continue; } if (file.isDirectory()) { copyDir(file, new File(toDir, file.getName()), filter); } else { copy(file, new File(toDir, file.getName())); } } }
/** * <根据URL下载图片,并保存到本地> <功能详细描述> * * @param imageURL * @param context * @return * @see [类、类#方法、类#成员] */ public static Bitmap loadImageFromUrl(String imageURL, File file, Context context) { Bitmap bitmap = null; try { URL url = new URL(imageURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.connect(); if (con.getResponseCode() == 200) { InputStream inputStream = con.getInputStream(); FileUtil.deleteDirectory(FileSystemManager.getUserHeadPath(context, Global.getUserId())); ByteArrayOutputStream OutputStream = new ByteArrayOutputStream(); FileOutputStream out = new FileOutputStream(file.getPath()); byte buf[] = new byte[1024 * 20]; int len = 0; while ((len = inputStream.read(buf)) != -1) { OutputStream.write(buf, 0, len); } OutputStream.flush(); OutputStream.close(); inputStream.close(); out.write(OutputStream.toByteArray()); out.close(); BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.inPreferredConfig = Bitmap.Config.RGB_565; imageOptions.inPurgeable = true; imageOptions.inInputShareable = true; bitmap = BitmapFactory.decodeFile(file.getPath(), imageOptions); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
/** * Returns relative path for any project's folder. If absolutePath has default location, returns * "__DEFAULT__". * * @param absolutePath absolute path to project folder. * @param defaultName default name for such a project's folder. * @since 1.6.0 */ private static String computeRelativePath( String m_root, String absolutePath, String defaultName) { if (absolutePath.equals(m_root + defaultName + File.separator)) return OConsts.DEFAULT_FOLDER_MARKER; try { // trying to look two folders up String res = absolutePath; File abs = new File(absolutePath).getCanonicalFile(); File root = new File(m_root).getCanonicalFile(); String prefix = new String(); for (int i = 0; i < 2; i++) { // File separator added to prevent "/MyProject EN-FR/" // to be undesrtood as being inside "/MyProject/" [1879571] if ((abs.getPath() + File.separator).startsWith(root.getPath() + File.separator)) { res = prefix + abs.getPath().substring(root.getPath().length()); if (res.startsWith(File.separator)) res = res.substring(1); break; } else { root = root.getParentFile(); prefix += File.separator + ".."; } } return res.replace(File.separatorChar, '/'); } catch (IOException e) { return absolutePath.replace(File.separatorChar, '/'); } }
@Test public void testGeneratedFiles() throws SAXException, IOException { final File[] files = { new File("maps", "root-map-01.ditamap"), new File("topics", "target-topic-a.xml"), new File("topics", "target-topic-c.xml"), new File("topics", "xreffin-topic-1.xml"), new File("topics", "copy-to.xml"), }; final Map<File, File> copyto = new HashMap<File, File>(); copyto.put(new File("topics", "copy-to.xml"), new File("topics", "xreffin-topic-1.xml")); final TestHandler handler = new TestHandler(); final XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(handler); for (final File f : files) { InputStream in = null; try { in = new FileInputStream(new File(tmpDir, f.getPath())); handler.setSource( new File(inputDir, copyto.containsKey(f) ? copyto.get(f).getPath() : f.getPath())); parser.parse(new InputSource(in)); } finally { if (in != null) { in.close(); } } } }
/** Saves the file back to disk. */ private void saveFile() { File file = getTargetFile().getFile(); Writer writer = null; Cursor originalcursor = this.getOwner().getCursor(); this.getOwner().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { CharsetEncoder encoder = getCharset().newEncoder(); if (encoder.canEncode(textArea.getText())) { writer = new OutputStreamWriter(new FileOutputStream(file), getCharset()); textArea.write(writer); messageBox.clear(); } else { findIllegalCharacter(encoder); } } catch (FileNotFoundException fnfx) { // happens also if file is RO logger.error("FileNotFoundException saving to " + file.getPath() + ": " + fnfx.getMessage()); messageBox.error(getLocalizer().localize("message.file-removed")); } catch (IOException iox) { logger.error("IOException saving file " + file.getPath() + ": " + iox.getMessage()); messageBox.error( getLocalizer() .localize("message.file-processing-error", new Object[] {iox.getMessage()})); } finally { this.getOwner().setCursor(originalcursor); if (writer != null) try { writer.close(); } catch (IOException iox) { logger.warn("IOException closing stream: " + iox.getMessage()); } } }
private StringBuffer getPOMPath(String groupId, String artifactId) { String fName = groupId.replace(PATH_SEPARATOR, GROUP_SEPARATOR) + "-" + artifactId + ".pom"; File f; // let's try maven 2 repo first f = new File("/usr/share/maven2/poms/" + fName); if (f.exists()) { return new StringBuffer(f.getPath()); } // now maven 3 specific repository f = new File("/usr/share/maven/poms/" + fName); if (f.exists()) { return new StringBuffer(f.getPath()); } // now try new path in /usr. This will be the only check after all // packages are rebuilt f = new File("/usr/share/maven-poms/" + fName); if (f.exists()) { return new StringBuffer(f.getPath()); } // final fallback to m2 default poms return new StringBuffer("/usr/share/maven2/default_poms/" + fName); }
@Override public void setData() { // gets all the files in the folder /characters File ogFile = new File(System.getProperty("user.dir") + "/characters"); ogFile.mkdir(); File[] characterFiles = Tools.listFilesForFolder(ogFile); for (int i = 0; i < characterFiles.length; i++) { File file = characterFiles[i]; // if they are .cdf files if (file.getPath().contains(".cdf")) { String[] parts = file.getPath().split("\\\\"); // add a row in the other characters dialog for them otherCharacterRows.add( new OtherCharacterRow(parts[parts.length - 1].replace(".cdf", ""), file, getRoot())); HBox row = otherCharacterRows.get(otherCharacterRows.size() - 1).getRow(); apOtherCharacters.getChildren().add(row); row.setLayoutY((row.getHeight() + 50) * i + 1); // if this is the first row, change the titled pane to say "Other Characters" rather than // "No Other Characters" if (!tpOtherCharacters.isExpanded()) { tpOtherCharacters.setExpanded(true); tpOtherCharacters.setText("Other Characters"); } } } }
public static void copyDirectory( File source, File destination, boolean hardLinks, FileFilter filter) { if (source.exists() && source.isDirectory()) { if (!destination.exists()) { destination.mkdirs(); } File[] fileArray = filter != null ? source.listFiles(filter) : source.listFiles(); for (int i = 0; i < fileArray.length; i++) { if (fileArray[i].getName().endsWith("xml")) { String name = fileArray[i].getName(); Logger.info(FileUtil.class, "copy " + name); } if (fileArray[i].isDirectory()) { copyDirectory( fileArray[i], new File(destination.getPath() + File.separator + fileArray[i].getName()), hardLinks, filter); } else { copyFile( fileArray[i], new File(destination.getPath() + File.separator + fileArray[i].getName()), hardLinks); } } } }
private void init() throws MojoExecutionException { try { if (StringUtils.isEmpty(buildNumber) || StringUtils.isEmpty(environmentName)) { callUsage(); } BuildInfo buildInfo = pUtil.getBuildInfo(Integer.parseInt(buildNumber)); buildDir = new File(baseDir.getPath() + BUILD_DIRECTORY); targetDir = new File(project.getBuild().getDirectory()); buildFile = new File(buildDir.getPath() + File.separator + buildInfo.getBuildName()); List<com.photon.phresco.configuration.Configuration> configurations = pUtil.getConfiguration(baseDir, environmentName, Constants.SETTINGS_TEMPLATE_SERVER); for (com.photon.phresco.configuration.Configuration configuration : configurations) { context = configuration.getProperties().getProperty(Constants.SERVER_CONTEXT); serverport = configuration.getProperties().getProperty(Constants.SERVER_PORT); serverprotocol = configuration.getProperties().getProperty(Constants.SERVER_PROTOCOL); break; } } catch (Exception e) { log.error(e); throw new MojoExecutionException(e.getMessage(), e); } }
private void extractBuild() throws MojoExecutionException { try { ArchiveUtil.extractArchive(buildFile.getPath(), targetDir.getPath(), ArchiveType.ZIP); } catch (PhrescoException e) { throw new MojoExecutionException(e.getErrorMessage(), e); } }
void run() throws Exception { File classesDir = new File("classes"); classesDir.mkdirs(); writeFile(baseFile, baseText); String[] javacArgs = {"-d", classesDir.getPath(), baseFile.getPath()}; com.sun.tools.javac.Main.compile(javacArgs); writeFile(srcFile, srcText); String[] args = { "-d", "api", "-classpath", classesDir.getPath(), "-package", "p", srcFile.getPath() }; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream prev = System.err; System.setErr(ps); try { int rc = com.sun.tools.javadoc.Main.execute(args); } finally { System.err.flush(); System.setErr(prev); } String out = baos.toString(); System.out.println(out); String errorMessage = "java.lang.IllegalArgumentException: <clinit>"; if (out.contains(errorMessage)) throw new Exception("error message found: " + errorMessage); }
/** @param f */ void loadParameters(File f) { try { parameters = new ParameterDatabase(f, clArgs); } catch (FileNotFoundException ex) { Output.initialError( "A File Not Found Exception was generated upon " + "reading the parameter file \"" + f.getPath() + "\".\nHere it is:\n" + ex); } catch (IOException ex) { Output.initialError( "An IO Exception was generated upon reading the " + "parameter file \"" + f.getPath() + "\".\nHere it is:\n" + ex); } if (parameters == null) { Output.initialError("No parameter file was loaded"); } else { paramPanel.loadParameters(); conPanel.loadParameters(); } }
/** * Copies all the mod files from the profileModDir to the factorioModDir. * * @param profileModDir The profileDir to copy mods from. * @param factorioModDir The factorioDir to copy mods to. * @param selectedNode The TreeNode that is currently selected. */ private void copyAllEnabledMods( File profileModDir, File factorioModDir, DefaultMutableTreeNode selectedNode) { // Let's copy all enabled mods! // Get the selected node. Enumeration<DefaultMutableTreeNode> children = selectedNode.children(); // Get it's children. while (children.hasMoreElements()) { DefaultMutableTreeNode node = children.nextElement(); // Get the next element. ModManagerWindow.CheckBoxNode checkBox = (ModManagerWindow.CheckBoxNode) node.getUserObject(); // Get the checkbox. String name = checkBox.getText(); // Get the text from the checkbox. if (name.equals("base") || !checkBox.isSelected()) continue; // If it is the "base" mod, ignore it (it's always on) // Get the file with the name of the mod and then copy it from the profile dir to the mods // dir. File file = FileUtils.findFileWithPartName( profileModDir, ((ModManagerWindow.CheckBoxNode) node.getUserObject()).getText()); try { Files.copy( file.toPath(), Paths.get( factorioModDir.getPath() + "/" + file.getPath().substring(file.getPath().lastIndexOf('\\')))); } catch (IOException e) { e.printStackTrace(); } } }
private static String findInDir(String key, String dir, OpenFileFilter off, int count) { if (count > 20) { return null; // Make sure an infinite loop doesn't occur. } File f = new File(dir); File[] all = f.listFiles(); if (all == null) { return null; // An error occured. We may not have // permission to list the files. } int numFiles = all.length; for (File curFile : all) { if (curFile.isFile()) { String name = curFile.getName(); if (name.startsWith(key + '.') && off.accept(name)) { return curFile.getPath(); } } else if (curFile.isDirectory()) { String found = UtilFindFiles.findInDir(key, curFile.getPath(), off, count + 1); if (found != null) { return found; } } } return null; }
/** * @param configPath * @param checkUserHome if true tries to check if the file ${user.home}/.pdfsam/config.xml exists * and can be written, if not tries to check if the file APPLICATIOH_PATH/config.xml can be * written, if not copies the APPLICATIOH_PATH/config.xml to ${user.home}/.pdfsam/config.xml * @throws Exception */ public XMLConfig(String configPath, boolean checkUserHome) throws Exception { File configFile = new File(configPath, "config.xml"); if (checkUserHome) { File defaultConfigFile = new File(defaultDirectory, "config.xml"); if (!(defaultConfigFile.exists() && defaultConfigFile.canWrite())) { if (!configFile.exists()) { throw new ConfigurationException("Unable to find configuration file."); } if (!configFile.canWrite()) { File defaultDir = new File(defaultDirectory); if (defaultDir.mkdirs()) { log.info( "Copying config.xml from " + configFile.getPath() + " to " + defaultConfigFile.getPath()); FileUtility.copyFile(configFile, defaultConfigFile); configFile = defaultConfigFile; } else { throw new ConfigurationException("Unable to create " + defaultDirectory); } } } else { configFile = defaultConfigFile; } } xmlConfigFile = configFile; document = XMLParser.parseXmlFile(xmlConfigFile); }
private void initializeWorkerStorage() throws IOException, FileDoesNotExistException, SuspectedFileSizeException, BlockInfoException, TException { LOG.info("Initializing the worker storage."); if (!mLocalDataFolder.exists()) { LOG.info("Local folder " + mLocalDataFolder + " does not exist. Creating a new one."); mLocalDataFolder.mkdirs(); mLocalUserFolder.mkdirs(); CommonUtils.changeLocalFilePermission(mLocalDataFolder.getPath(), "775"); CommonUtils.changeLocalFilePermission(mLocalUserFolder.getPath(), "775"); return; } if (!mLocalDataFolder.isDirectory()) { String tmp = "Data folder " + mLocalDataFolder + " is not a folder!"; LOG.error(tmp); throw new IllegalArgumentException(tmp); } if (mLocalUserFolder.exists()) { try { FileUtils.deleteDirectory(mLocalUserFolder); } catch (IOException e) { LOG.error(e.getMessage(), e); } } mLocalUserFolder.mkdir(); CommonUtils.changeLocalFilePermission(mLocalUserFolder.getPath(), "775"); mUnderfsOrphansFolder = mUnderfsWorkerFolder + "/orphans"; if (!mUnderFs.exists(mUnderfsOrphansFolder)) { mUnderFs.mkdirs(mUnderfsOrphansFolder, true); } int cnt = 0; for (File tFile : mLocalDataFolder.listFiles()) { if (tFile.isFile()) { cnt++; LOG.info("File " + cnt + ": " + tFile.getPath() + " with size " + tFile.length() + " Bs."); long blockId = CommonUtils.getBlockIdFromFileName(tFile.getName()); boolean success = mWorkerSpaceCounter.requestSpaceBytes(tFile.length()); try { addFoundBlock(blockId, tFile.length()); } catch (FileDoesNotExistException e) { LOG.error("BlockId: " + blockId + " becomes orphan for: \"" + e.message + "\""); LOG.info( "Swapout File " + cnt + ": blockId: " + blockId + " to " + mUnderfsOrphansFolder); swapoutOrphanBlocks(blockId, tFile); freeBlock(blockId); continue; } mAddedBlockList.add(blockId); if (!success) { throw new RuntimeException("Pre-existing files exceed the local memory capacity."); } } } }
/** * Load the config from the default config file and create the singleton instance of this factory. * * @exception java.io.IOException Thrown if the specified config file cannot be read * @exception org.exolab.castor.xml.MarshalException Thrown if the file does not conform to the * schema. * @exception org.exolab.castor.xml.ValidationException Thrown if the contents do not match the * required schema. * @throws java.io.IOException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static synchronized void init() throws IOException, MarshalException, ValidationException { if (m_loaded) { // init already called - return // to reload, reload() will need to be called return; } final File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.DISCOVERY_CONFIG_FILE_NAME); LogUtils.debugf(DiscoveryConfigFactory.class, "init: config file path: %s", cfgFile.getPath()); m_singleton = new DiscoveryConfigFactory(cfgFile.getPath()); try { m_singleton.getInitialSleepTime(); m_singleton.getRestartSleepTime(); m_singleton.getIntraPacketDelay(); m_singleton.getConfiguredAddresses(); } catch (final Exception e) { throw new ValidationException( "An error occurred while validating the configuration: " + e, e); } m_loaded = true; }
/** Creates lookup/search files with the given values under the given directory. */ private void createLookupFiles(File dirHandle, String attr, Set sunserviceids) throws SMSException { StringBuilder sb = new StringBuilder(dirHandle.getPath()); sb.append(File.separatorChar); sb.append(attr); sb.append('='); String fileprefix = sb.toString(); for (Iterator i = sunserviceids.iterator(); i.hasNext(); ) { String id = ((String) i.next()).toLowerCase(); File idFile = new File(fileprefix + id); try { idFile.createNewFile(); } catch (IOException e) { String errmsg = "SMSFlatFileObject.createLookupIdFiles: " + " File, " + idFile.getPath() + ". Exception: " + e.getMessage(); mDebug.error("SMSFlatFileObject.createLookupIdFiles", e); throw new SMSException(errmsg); } } }
/** Create a File for saving an image or video */ private static File getOutputMediaFile(int type) { // To be safe, you should check that the SDCard is mounted // using Environment.getExternalStorageState() before doing this. File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp"); // This location works best if you want the created images to be shared // between applications and persist after your app has been uninstalled. // Create the storage directory if it does not exist if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; } } // Create a media file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else if (type == MEDIA_TYPE_VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; }
private void scan(String pattern) { LOGGER.fine("Scanning " + pattern + " for hs_err_pid files"); pattern = pattern.replace("%p", "*").replace("%%", "%"); File f = new File(pattern).getAbsoluteFile(); if (!pattern.contains("*")) scanFile(f); else { // GLOB File commonParent = f; while (commonParent != null && commonParent.getPath().contains("*")) { commonParent = commonParent.getParentFile(); } if (commonParent == null) { LOGGER.warning("Failed to process " + f); return; // huh? } FileSet fs = Util.createFileSet( commonParent, f.getPath().substring(commonParent.getPath().length() + 1), null); DirectoryScanner ds = fs.getDirectoryScanner(new Project()); for (String child : ds.getIncludedFiles()) { scanFile(new File(commonParent, child)); } } }
/** * Adjusts the project location to make it absolute & canonical relative to the working directory, * if any. * * @return The project absolute path relative to {@link #mWorkDir} or the original * newProjectLocation otherwise. */ private String getProjectLocation(String newProjectLocation) { // If the new project location is absolute, use it as-is File projectDir = new File(newProjectLocation); if (projectDir.isAbsolute()) { return newProjectLocation; } // if there's no working directory, just use the project location as-is. if (mWorkDir == null) { return newProjectLocation; } // Combine then and get an absolute canonical directory try { projectDir = new File(mWorkDir, newProjectLocation).getCanonicalFile(); return projectDir.getPath(); } catch (IOException e) { errorAndExit( "Failed to combine working directory '%1$s' with project location '%2$s': %3$s", mWorkDir.getPath(), newProjectLocation, e.getMessage()); return null; } }
/** * Method to read the content of a file into a String and return it * * @param file a File to be read * @return a String object containing the content of the file */ protected String readFileIntoString(File file) { StringBuilder fileContentsBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { char[] buffer = new char[32767]; bufferedReader = new BufferedReader(new FileReader(file)); int read = 0; do { read = bufferedReader.read(buffer); if (read > 0) { fileContentsBuilder.append(buffer, 0, read); } } while (read > 0); } catch (Exception e) { log.error("Failed to read file " + file.getPath(), e); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { log.error("Unable to close BufferedReader for " + file.getPath(), e); } } } return fileContentsBuilder.toString(); }
/** * 保存Bitmap到手机缓存 * * @param bm * @param savePath * @param fileName * @param context */ public void saveBitmapToMobileCache( Bitmap bm, String savePath, String fileName, Context context) { if (bm == null) { Log.w(TAG, " trying to savenull bitmap"); return; } File path = context.getCacheDir(); File fileFolder = new File(path.getPath() + "/" + savePath); if (!fileFolder.exists()) { fileFolder.mkdirs(); } File saveFile = new File(fileFolder.getPath() + "/" + fileName); try { if (!saveFile.exists()) { saveFile.createNewFile(); OutputStream outStream = new FileOutputStream(saveFile); bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); Log.e("saveFile", saveFile.length() + ""); Log.i(TAG, "Image saved tosd"); } } catch (Exception e) { Log.w(TAG, e.getMessage()); } }
/* Uses resource to create default file, if file does not yet exist */ public boolean createDefaultFileFromResource(String resourcename, File deffile) { if (deffile.canRead()) return true; Log.info(deffile.getPath() + " not found - creating default"); InputStream in = getClass().getResourceAsStream(resourcename); if (in == null) { Log.severe("Unable to find default resource - " + resourcename); return false; } else { FileOutputStream fos = null; try { fos = new FileOutputStream(deffile); byte[] buf = new byte[512]; int len; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } catch (IOException iox) { Log.severe("ERROR creatomg default for " + deffile.getPath()); return false; } finally { if (fos != null) try { fos.close(); } catch (IOException iox) { } if (in != null) try { in.close(); } catch (IOException iox) { } } return true; } }
@Override public void updateFileVersion( long companyId, long repositoryId, String fileName, String fromVersionLabel, String toVersionLabel) throws DuplicateFileException, NoSuchFileException { File fromFileNameVersionFile = getFileNameVersionFile(companyId, repositoryId, fileName, fromVersionLabel); if (!fromFileNameVersionFile.exists()) { throw new NoSuchFileException(companyId, repositoryId, fileName, fromVersionLabel); } File toFileNameVersionFile = getFileNameVersionFile(companyId, repositoryId, fileName, toVersionLabel); if (toFileNameVersionFile.exists()) { throw new DuplicateFileException(companyId, repositoryId, fileName, toVersionLabel); } boolean renamed = FileUtil.move(fromFileNameVersionFile, toFileNameVersionFile); if (!renamed) { throw new SystemException( "File name version file was not renamed from " + fromFileNameVersionFile.getPath() + " to " + toFileNameVersionFile.getPath()); } }
/** * Scan all output dirs for artifacts and remove those files (artifacts?) that are not recognized * as such, in the javac_state file. */ public void removeUnidentifiedArtifacts() { Set<File> allKnownArtifacts = new HashSet<>(); for (Package pkg : prev.packages().values()) { for (File f : pkg.artifacts().values()) { allKnownArtifacts.add(f); } } // Do not forget about javac_state.... allKnownArtifacts.add(javacState); for (File f : binArtifacts) { if (!allKnownArtifacts.contains(f)) { Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state."); f.delete(); } } for (File f : headerArtifacts) { if (!allKnownArtifacts.contains(f)) { Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state."); f.delete(); } } for (File f : gensrcArtifacts) { if (!allKnownArtifacts.contains(f)) { Log.debug("Removing " + f.getPath() + " since it is unknown to the javac_state."); f.delete(); } } }