// Variant which breaks public File encoddeAnyToUTF81(String filepath, String Charset, String ext) { File f = new File(filepath); String globalFileName = f.getParent() + "/tempFile" + ext; try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filepath), Charset)); String ch; ByteArrayOutputStream readbuff = new ByteArrayOutputStream(); BufferedOutputStream buffOutS = new BufferedOutputStream(readbuff); while ((ch = br.readLine()) != null) { byte[] b = ch.getBytes("UTF-8"); readbuff.write(b); } br.close(); f.delete(); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(f.getParent() + "/tempFile" + ext), "UTF-8"); writer.write(readbuff.toString()); writer.close(); readbuff.close(); } catch (Exception e) { e.printStackTrace(); } return new File(globalFileName); }
// Variant work slowly public File encodeCP866ToUTF82(String filepath, String Charset) { File file = new File(filepath); try { BufferedInputStream buff = new BufferedInputStream(new FileInputStream(filepath)); String readbuff = ""; String TmpBuff = ""; int count250 = 0; int ch; while ((ch = buff.read()) > -1) { if (TmpBuff.length() > 5000) { count250++; TmpBuff = ""; } readbuff += lookup[ch]; TmpBuff += lookup[ch]; } buff.close(); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file.getParent() + "/tempFile.txt"), "UTF-8"); writer.write(readbuff.toString()); writer.close(); } catch (Exception e) { e.printStackTrace(); } return new File(file.getParent() + "/tempFile.txt"); }
/** * Simulate the <code>dfs.name.dir</code> or <code>dfs.data.dir</code> of a populated DFS * filesystem. * * <p>This method creates and populates the directory specified by <code>parent/dirName</code>, * for each parent directory. The contents of the new directories will be appropriate for the * given node type. If the directory does not exist, it will be created. If the directory already * exists, it will first be deleted. * * <p>By default, a singleton master populated storage directory is created for a Namenode * (contains edits, fsimage, version, and time files) and a Datanode (contains version and block * files). These directories are then copied by this method to create new storage directories of * the appropriate type (Namenode or Datanode). * * @return the array of created directories */ public static File[] createStorageDirs(NodeType nodeType, String[] parents, String dirName) throws Exception { File[] retVal = new File[parents.length]; for (int i = 0; i < parents.length; i++) { File newDir = new File(parents[i], dirName); createEmptyDirs(new String[] {newDir.toString()}); LocalFileSystem localFS = FileSystem.getLocal(new Configuration()); switch (nodeType) { case NAME_NODE: localFS.copyToLocalFile( new Path(namenodeStorage.toString(), "current"), new Path(newDir.toString()), false); Path newImgDir = new Path(newDir.getParent(), "image"); if (!localFS.exists(newImgDir)) localFS.copyToLocalFile( new Path(namenodeStorage.toString(), "image"), newImgDir, false); break; case DATA_NODE: localFS.copyToLocalFile( new Path(datanodeStorage.toString(), "current"), new Path(newDir.toString()), false); Path newStorageFile = new Path(newDir.getParent(), "storage"); if (!localFS.exists(newStorageFile)) localFS.copyToLocalFile( new Path(datanodeStorage.toString(), "storage"), newStorageFile, false); break; } retVal[i] = newDir; } return retVal; }
private void writeFailedMarker(final File deploymentFile, final ModelNode failureDescription) { final File failedMarker = new File(deploymentFile.getParent(), deploymentFile.getName() + FAILED_DEPLOY); final File deployMarker = new File(deploymentFile.getParent(), deploymentFile.getName() + DO_DEPLOY); if (deployMarker.exists() && !deployMarker.delete()) { log.warnf("Unable to remove marker file %s", deployMarker); } final File deployedMarker = new File(deploymentFile.getParent(), deploymentFile.getName() + DEPLOYED); if (deployedMarker.exists() && !deployedMarker.delete()) { log.warnf("Unable to remove marker file %s", deployedMarker); } FileOutputStream fos = null; try { failedMarker.createNewFile(); fos = new FileOutputStream(failedMarker); fos.write(failureDescription.asString().getBytes()); } catch (IOException io) { log.errorf( io, "Caught exception writing deployment failed marker file %s", failedMarker.getAbsolutePath()); } finally { safeClose(fos); } }
/** Convenience method to load the comments for this blog entry. A blog entry can have */ public void loadComments() { if (supportsComments()) { String commentsDirectoryPath; if (_source.getParent() == null) { commentsDirectoryPath = File.separator + _commentsDirectory + File.separator + _source.getName(); } else { commentsDirectoryPath = _source.getParent() + File.separator + _commentsDirectory + File.separator + _source.getName(); } File commentsDirectory = new File(commentsDirectoryPath); File[] comments = commentsDirectory.listFiles(BlojsomUtils.getExtensionFilter(COMMENT_EXTENSION)); if ((comments != null) && (comments.length > 0)) { _logger.debug("Adding " + comments.length + " comments to blog entry: " + getPermalink()); Arrays.sort(comments, BlojsomUtils.FILE_TIME_ASCENDING_COMPARATOR); _comments = new ArrayList(comments.length); for (int i = 0; i < comments.length; i++) { File comment = comments[i]; _comments.add(loadComment(comment)); } } } else { _logger.debug("Blog entry does not support comments"); } }
/** * * * <pre> * <b>Description:</b> * Function remove folder from ftp * <b>Creation date: </b>02.05.08 * <b>Modification date: </b>02.05.08 * </pre> * * @param String sDirPath � removed directory * @author Vitalii Fedorets * @return boolean � true if success */ public boolean removeFolder(String sDirPath) throws Exception { try { File oDir = new File(sDirPath); FTPClient oFtp = this.initFtpClientLoginChangeWorkingDirectory(sDirPath); oFtp.changeWorkingDirectory(oDir.getParent().replace("\\", "/")); int iReply = oFtp.getReplyCode(); if (!FTPReply.isPositiveCompletion(iReply)) { log.setError("Not change work directory to `" + oDir.getParent().replace("\\", "/") + "`"); oFtp.disconnect(); return false; } if (!oFtp.removeDirectory(sDirPath)) { log.setError("Could not remove directory `" + sDirPath + "`"); oFtp.disconnect(); return false; } return true; } catch (Exception oEx) { throw oEx; } }
public static File generateUniqueSampleDirFrom(String baseName, File dir) { int index = 1; int copyIndex = baseName.lastIndexOf("-"); // $NON-NLS-1$ if (copyIndex > -1) { String trailer = baseName.substring(copyIndex + 1); if (isNumber(trailer)) { try { index = Integer.parseInt(trailer); baseName = baseName.substring(0, copyIndex); } catch (NumberFormatException nfe) { } } } String newName = baseName; File newDir = new File(dir.getParent(), newName); while (newDir.exists()) { newName = MessageFormat.format( IntroMessages.IntroEditor_projectName, new Object[] {baseName, Integer.toString(index)}); index++; newDir = new File(dir.getParent(), newName); } return newDir; }
public void save() throws IOException { FileOutputStream out = null; ObjectOutputStream s = null; try { File file = new File(getPersistentFileName()); if (!file.exists()) { if (file.getParent() != null) { new File(file.getParent()).mkdirs(); } file.createNewFile(); } out = new FileOutputStream(file); s = new ObjectOutputStream(out); s.writeObject(this); this.isExist = true; } finally { if (s != null) { try { s.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e1) { e1.printStackTrace(); } } } }
/** * 真正的解压方法 会删除解压完的所有Zip文档 * * @param File 一个。zip的 文件 */ public static void myzijide(File file) throws IOException { ZipInputStream zip = new ZipInputStream(new FileInputStream(file)); ZipEntry en = null; BufferedOutputStream out = null; // 循环读取ZIP文件中的内容 while ((en = zip.getNextEntry()) != null) { if (en.isDirectory()) { File f = new File(file.getParent() + "\\" + en.getName()); if (!f.exists()) f.mkdirs(); continue; } // 发现好多文件夹存在 Thumbs , 定一个识别将他过滤 // 文件名中含有Thumbs 将 不 解压 if (en.getName().contains("Thumbs")) { continue; } // 实际的输出方法 out = new BufferedOutputStream(new FileOutputStream(file.getParent() + "\\" + en.getName())); int i = -1; byte[] b = new byte[1024]; while ((i = zip.read(b)) != -1) { out.write(b, 0, i); } out.close(); } zip.close(); // 删除文件 String tishi = file.delete() ? "yes" : "no"; System.out.println(file.getName() + "解压完成并删除 ?" + tishi); }
@Test public void copyFromLocalTest() throws IOException, TException { File testDir = new File(mLocalTachyonCluster.getTachyonHome() + "/testDir"); testDir.mkdir(); File testDirInner = new File(mLocalTachyonCluster.getTachyonHome() + "/testDir/testDirInner"); testDirInner.mkdir(); File testFile = generateFileContent("/testDir/testFile", BufferUtils.getIncreasingByteArray(10)); generateFileContent( "/testDir/testDirInner/testFile2", BufferUtils.getIncreasingByteArray(10, 20)); mFsShell.copyFromLocal(new String[] {"copyFromLocal", testFile.getParent(), "/testDir"}); Assert.assertEquals( getCommandOutput(new String[] {"copyFromLocal", testFile.getParent(), "/testDir"}), mOutput.toString()); TachyonFile file1 = mTfs.open(new TachyonURI("/testDir/testFile")); TachyonFile file2 = mTfs.open(new TachyonURI("/testDir/testDirInner/testFile2")); FileInfo fileInfo1 = mTfs.getInfo(file1); FileInfo fileInfo2 = mTfs.getInfo(file2); Assert.assertNotNull(fileInfo1); Assert.assertNotNull(fileInfo2); Assert.assertEquals(10, fileInfo1.length); Assert.assertEquals(20, fileInfo2.length); byte[] read = readContent(file1, 10); Assert.assertTrue(BufferUtils.equalIncreasingByteArray(10, read)); read = readContent(file2, 20); Assert.assertTrue(BufferUtils.equalIncreasingByteArray(10, 20, read)); }
/** Convenience method to load the trackbacks for this blog entry. */ public void loadTrackbacks() { String trackbacksDirectoryPath; if (_source.getParent() == null) { trackbacksDirectoryPath = File.separator + _trackbacksDirectory + File.separator + _source.getName(); } else { trackbacksDirectoryPath = _source.getParent() + File.separator + _trackbacksDirectory + File.separator + _source.getName(); } File trackbacksDirectory = new File(trackbacksDirectoryPath); File[] trackbacks = trackbacksDirectory.listFiles(BlojsomUtils.getExtensionFilter(TRACKBACK_EXTENSION)); if ((trackbacks != null) && (trackbacks.length > 0)) { _logger.debug("Adding " + trackbacks.length + " trackbacks to blog entry: " + getPermalink()); Arrays.sort(trackbacks, BlojsomUtils.FILE_TIME_ASCENDING_COMPARATOR); _trackbacks = new ArrayList(trackbacks.length); for (int i = 0; i < trackbacks.length; i++) { File trackbackFile = trackbacks[i]; _trackbacks.add(loadTrackback(trackbackFile)); } } }
/** * When loading profiles, check that XMI profile dependency resolution is handled correctly when * two user defined profiles are handed to {@link ProfileManagerImpl#loadProfiles(List)} in two * calls, with the first call handing the dependent profile of the second and only on the second * call being handed the profile from which the first depends. * * @throws IOException when file IO goes wrong... * @throws UmlException when UML manipulation goes wrong... */ public void testXmiProfileDependencyResolutionWithProfilesHandedInReverseOrderOfDependencyInTwoCalls() throws IOException, UmlException { List<Profile> registeredProfiles = manager.getRegisteredProfiles(); int numRegisteredBefore = registeredProfiles.size(); ProfileMother mother = new ProfileMother(); List<File> profileFiles = mother.createUnloadedProfilePairWith2ndDependingOn1stViaXmi(); File dependentProfileFile = profileFiles.get(1); File baseProfileFile = profileFiles.get(0); ArrayList<File> dependentProfileList = new ArrayList<File>(); dependentProfileList.add(dependentProfileFile); ProfileManagerImpl managerImpl = (ProfileManagerImpl) manager; manager.addSearchPathDirectory(baseProfileFile.getParent()); managerImpl.loadProfiles(dependentProfileList); assertEquals( "We should have one more registered profiles as in the beginning.", numRegisteredBefore + 1, manager.getRegisteredProfiles().size()); ArrayList<File> baseProfileList = new ArrayList<File>(); baseProfileList.add(baseProfileFile); managerImpl.loadProfiles(baseProfileList); assertEquals( "Now we should have two more registered profiles.", numRegisteredBefore + 2, manager.getRegisteredProfiles().size()); manager.removeSearchPathDirectory(baseProfileFile.getParent()); }
/** * Takes a screenshot and saves the image to disk, in JPEG format. * * @param destination Path and filename for the created image. If the extension is not ".jpeg" * (case-insensitive), ".jpeg" will be appended to the filename. * @param delay Amount of time to wait (in milliseconds) before taking the screenshot. * @param fileAccess Determines how the file will be created if a file with the given name and * path already exists:<br> * <code>SwingApplicationImplClass.RENAME</code> - The screenshot will be saved with a * sequential integer appended to the filename.<br> * <code>SwingApplicationImplClass.OVERWRITE</code> - The screenshot will overwrite the file. * @param scaling Degree to which the image should be scaled, in percent. A <code>scaling</code> * value of <code>100</code> produces an unscaled image. This value must be greater than * <code>0</code> and less than or equal to <code>200</code>. * @param createDirs Determines whether a path will be created if it does not already exist. A * value of <code>true</code> means that all necessary directories that do not exist will be * created automatically. * @param screenShotRect the rectangle to take the screenshot of */ private void takeScreenshot( String destination, int delay, String fileAccess, int scaling, boolean createDirs, Rectangle screenShotRect) { if (scaling <= 0 || scaling > 200) { throw new StepExecutionException( "Invalid scaling factor: Must be between 1 and 200", //$NON-NLS-1$ EventFactory.createActionError(TestErrorEvent.INVALID_PARAM_VALUE)); } double scaleFactor = scaling * 0.01; // Check if file name is valid String outFileName = destination; String imageExtension = getExtension(outFileName); if (imageExtension.length() == 0) { // If not, then we simply append the default extension imageExtension = DEFAULT_IMAGE_FORMAT; outFileName += EXTENSION_SEPARATOR + imageExtension; } // Wait for a user-specified time if (delay > 0) { TimeUtil.delay(delay); } // Create path, if necessary File pic = new File(outFileName); if (pic.getParent() == null) { throw new StepExecutionException( "Invalid file name: specify a file name", //$NON-NLS-1$ EventFactory.createActionError(TestErrorEvent.INVALID_PARAM_VALUE)); } File path = new File(pic.getParent()); if (createDirs && !path.exists() && !path.mkdirs()) { throw new StepExecutionException( "Directory path does not exist and could not be created", //$NON-NLS-1$ EventFactory.createActionError(TestErrorEvent.FILE_IO_ERROR)); } // Rename file if file already exists // FIXME zeb This naming scheme can lead to sorting problems when // filenames have varying numbers of digits (ex. "pic_9" and // "pic_10") if (fileAccess.equals(RENAME)) { String completeExtension = EXTENSION_SEPARATOR + imageExtension.toLowerCase(); int extensionIndex = pic.getName().toLowerCase().lastIndexOf(completeExtension); String fileName = pic.getName().substring(0, extensionIndex); for (int i = 1; pic.exists(); i++) { pic = new File(pic.getParent(), fileName + "_" + i + completeExtension); // $NON-NLS-1$ } } takeScreenshot(screenShotRect, scaleFactor, pic); }
/** {@inheritDoc} */ @Override public void startDocument() throws SAXException { LOG.debug("Starting XML parsing"); // XmlToken XmlToken token = new XmlToken(); token.setLine(locator.getLineNumber()); token.setColumn(locator.getColumnNumber()); token.setType(XmlTokenTypes.DOCUMENT); token.setText(file.getName()); // Node root = new DetailAST(); root.initialize(token); currentNode = root; // Path = package token = new XmlToken(); token.setLine(locator.getLineNumber()); token.setColumn(locator.getColumnNumber()); token.setType(XmlTokenTypes.PATH); token.setText(file.getParent()); DetailAST path = new DetailAST(); path.initialize(token); root.addChild(path); DetailAST pathIdent = new DetailAST(); token = new XmlToken(); token.setLine(locator.getLineNumber()); token.setColumn(locator.getColumnNumber()); token.setType(XmlTokenTypes.IDENT); token.setText(file.getParent()); pathIdent.initialize(token); path.addChild(pathIdent); // Fake child to match Java grammar structure pathIdent = new DetailAST(); pathIdent.initialize(token); path.addChild(pathIdent); // Name = Type token = new XmlToken(); token.setLine(locator.getLineNumber()); token.setColumn(locator.getColumnNumber()); token.setType(XmlTokenTypes.IDENT); token.setText(file.getName()); DetailAST name = new DetailAST(); name.initialize(token); root.addChild(name); DetailAST nameIdent = new DetailAST(); token = new XmlToken(); token.setLine(locator.getLineNumber()); token.setColumn(locator.getColumnNumber()); token.setType(XmlTokenTypes.IDENT); token.setText(file.getName()); nameIdent.initialize(token); name.addChild(nameIdent); }
private void parseInclude(MyStringTokenizer st) throws IOException { if (!st.hasMoreTokens()) throw new IOException("Missing file to include"); File newfile; String filename = st.nextToken(); if (file.getParent() == null) newfile = new File(filename); else newfile = new File(file.getParent(), filename); if (st.hasMoreTokens()) included = new Master(newfile, new Name(st.nextToken())); else included = new Master(newfile, origin); }
/** * 文件解压到默认目录 * * @param file 压缩文件 * @param onSite true-当前目录|false-文件名目录 */ public static void decompress(File file, boolean onSite) { if (onSite) { CompressUtilsHelper.decompress(file, new File(file.getParent()), DEFAULT_ENCODING); return; } String dirName = FilenameUtils.getName(file.getName()); File dir = new File(file.getParent(), dirName); CompressUtilsHelper.decompress(file, dir, DEFAULT_ENCODING); }
// This function reads the file and sets each line to their appropriate value // Note, the file must be in the same folder as the working directory/project folder public boolean readInventory(String filename) { String line = ""; int numBooks; m_InFile = new File(filename); if (!m_InFile.exists()) { // m_InFile.exists() returns false if the file could not be found or // if for some other reason the open failed. System.err.println( "Unable to open file " + filename + " in path" + m_InFile.getParent() + "\nProgram terminating...\n"); return false; } if (!(m_InFile.toString().contains("txt"))) { System.err.println("Sorr but " + filename + " does not have file extension of .txt"); } try { reader = new FileReader(filename); Bufreader = new BufferedReader(reader); } catch (FileNotFoundException e) { System.err.println("Sorry but " + filename + " is not found in" + m_InFile.getParent()); } // Read number of books, should be the first number in the inventory file line = getNextLine(line); numBooks = Integer.parseInt(line); // converts the number of books to an integer value for (int i = 0; i < numBooks; i++) { // The first loop creates a new Book Record for each book in the file. // The nested for loop to reach the five lines that create a Book Record. // The if statements sort out each line and set them to their appropriate values. // When the last line is reached, the book is added to the list. BookRecord Book = new BookRecord(); int j = 1; while (j <= 5) { line = getNextLine(line); if (j == 1) { Book.setStockNum(Long.parseLong(line)); } else if (j == 2) { Book.setName(line.toString()); } else if (j == 3) { Book.setClassification(Integer.parseInt(line)); } else if (j == 4) { Book.setCost(Double.parseDouble(line)); } else if (j == 5) { Book.setNumberInStock(Integer.parseInt(line)); addBook(Book); } j++; } } return true; }
public void testGetParent() throws IOException { File file = fs.getFile("file.txt"); assertEquals(file.getParent(), null); file = fs.getFile("/parentdir/file.txt"); assertEquals(file.getParent(), "/parentdir"); file = fs.getFile("/parentdir/subdir/file.txt"); assertEquals(file.getParent(), "/parentdir/subdir"); }
/** * ************************************************************** getView the overridden getView * method */ public View getView(int position, View convertView, ViewGroup parent) { // update the text accordingly File f = new File(getItem(position)); int imageid; if (f.isDirectory()) imageid = R.drawable.fileicon_folder; else { String ext = getFileExtension(getItem(position)); if (ext.equals("c")) imageid = R.drawable.fileicon_c; else if (ext.equals("cpp")) imageid = R.drawable.fileicon_cpp; else if (ext.equals("f")) imageid = R.drawable.fileicon_f; else if (ext.equals("h")) imageid = R.drawable.fileicon_h; else if (ext.equals("htm")) imageid = R.drawable.fileicon_htm; else if (ext.equals("html")) imageid = R.drawable.fileicon_html; else if (ext.equals("java")) imageid = R.drawable.fileicon_java; else if (ext.equals("pl")) imageid = R.drawable.fileicon_pl; else if (ext.equals("py")) imageid = R.drawable.fileicon_py; else if (ext.equals("tex")) imageid = R.drawable.fileicon_tex; else if (ext.equals("txt")) imageid = R.drawable.fileicon_txt; else imageid = R.drawable.fileicon_default; } // This really speeds things up. Because only the number of views displayed at one time // are actually inflated View textEntryView; if (convertView != null) textEntryView = convertView; else textEntryView = factory.inflate(R.layout.filebrowser_item, null); TextView tv = (TextView) textEntryView.findViewById(R.id.itemtext); tv.setText(getItem(position)); ImageView iv = (ImageView) textEntryView.findViewById(R.id.itemimage); iv.setImageResource(imageid); if (mode == FILE_BROWSER_MODE) { Spannable text = sf.newSpannable(f.getName() + formatFileSize(f)); text.setSpan( new AbsoluteSizeSpan(20), 0, f.getName().length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tv.setText(text); } else { // default to RECENT_FILE_MODE Spannable text; if (f.getParent().toString().equals("/")) text = sf.newSpannable(f.getName() + "\n/"); else text = sf.newSpannable(f.getName() + "\n" + f.getParent() + "/"); text.setSpan( new AbsoluteSizeSpan(20), 0, f.getName().length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); tv.setText(text); } return textEntryView; } // end getView()
public int compare(File a, File b) { String aLowerCaseName = a.getName().toLowerCase(Locale.US); String bLowerCaseName = b.getName().toLowerCase(Locale.US); return new CompareToBuilder() .append(a.getParent(), b.getParent(), ALPHA_NUMERIC_STRING_COMPARATOR) .append(a.isDirectory(), b.isDirectory()) .append(!aLowerCaseName.startsWith("demo"), !bLowerCaseName.startsWith("demo")) .append(aLowerCaseName, bLowerCaseName, ALPHA_NUMERIC_STRING_COMPARATOR) .append(a.getName(), b.getName()) .toComparison(); }
/** * Write a list of pages to the xml file * * @param pageList A List<Page> object * @param XmlFilePath Full path to an xml file */ public void writePagesToXml(List<Page> pageList, String XmlFilePath) { File f = new File(XmlFilePath); // Create folders if required if (f.getParent() != null) { new File(f.getParent()).mkdirs(); } // Create all IndexPage entries AttributesImpl a = new AttributesImpl(); for (Page s : pageList) { if (s instanceof IndexPage) { ((IndexPage) s).index(pageList); a.addAttribute( "", WikiDocletCfg.WIKI_DOCLET_INDEX_PAGE_NAME_ATTRIBUTE, "", "", s.getPageTitle()); } } try { // Create file writer FileWriter f0 = new FileWriter(f); // Create new XML XMLWriterHandler xmlwriter = new XMLWriterHandler(f0); // Start xml document xmlwriter.startDocument(); // Root node xmlwriter.startElement("", WikiDocletCfg.WIKI_DOCLET_XML_ROOT, "", a); // Create page entry for each page for (Page s : pageList) { LOGGER.debug("Writing page " + s.getPageTitle()); xmlwriter.startElement(WikiDocletCfg.WIKI_DOCLET_XML_PAGE); xmlwriter.dataElement(WikiDocletCfg.WIKI_DOCLET_XML_TITLE, s.getPageTitle()); xmlwriter.dataElement( WikiDocletCfg.WIKI_DOCLET_XML_CONTENT, stripNonValidXMLCharacters(s.toString())); xmlwriter.dataElement(WikiDocletCfg.WIKI_DOCLET_XML_HASH, s.getHash()); xmlwriter.dataElement( WikiDocletCfg.WIKI_DOCLET_XML_TIME, Long.toString(new Date().getTime())); xmlwriter.endElement(WikiDocletCfg.WIKI_DOCLET_XML_PAGE); } // Close root node xmlwriter.endElement(WikiDocletCfg.WIKI_DOCLET_XML_ROOT); // Close xml document xmlwriter.endDocument(); } catch (IOException e) { LOGGER.error("XML file could not be written.", e); } catch (SAXException e) { LOGGER.error("XML file could not be written.", e); } }
@SuppressWarnings({"unchecked", "ResultOfMethodCallIgnored"}) public void newRecord(String code, String name, String age, String city, String oldest) { try { if (!backUp.exists()) { new File(backUp.getParent()).mkdirs(); } if (F.exists()) { FIS = new FileInputStream(F); OIS = new ObjectInputStream(FIS); records = (ArrayList<Record>) OIS.readObject(); OIS.close(); FIS.close(); } FOS = new FileOutputStream(F); OOS = new ObjectOutputStream(FOS); records.add(new Record(code, name, age, city, oldest)); OOS.writeObject(records); OOS.close(); FOS.close(); // SAVING BACKUP... if (backUp.exists()) { FIS = new FileInputStream(backUp); OIS = new ObjectInputStream(FIS); records = (ArrayList<Record>) OIS.readObject(); OIS.close(); FIS.close(); } FOS = new FileOutputStream(backUp); OOS = new ObjectOutputStream(FOS); records.add(new Record(code, name, age, city, oldest)); OOS.writeObject(records); OOS.close(); FOS.close(); // BACKUP SAVED! System.err.println("Successfully saved on: " + F.getParent()); } catch (Exception e) { e.printStackTrace(); } }
private static void unZipZipInputStream(ZipInputStream zis, String outFolder) throws IOException { String outputFolder = outFolder; if (outputFolder == null) { outputFolder = System.getProperty("user.dir"); } // create output directory is not exists File folder = new File(outputFolder); if (!folder.exists()) { folder.mkdirs(); } ZipEntry ze = zis.getNextEntry(); while (ze != null) { byte[] buffer = new byte[1024]; String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); // System.out.println("file unzip : "+ newFile.getAbsoluteFile()); // create all non exists folders // else you will hit FileNotFoundException for compressed folder // new File(newFile.getParent()).mkdirs(); if (newFile.isDirectory()) { newFile.mkdirs(); ze = zis.getNextEntry(); continue; } if (newFile.getParent() != null) { File parent = new File(newFile.getParent()); parent.mkdirs(); } FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); // System.out.println("Done"); }
public void onDismiss(EditNameFragment dialog) { if (dialog instanceof EditNameFragment) { if (((EditNameFragment) dialog).getResult()) { String newFilename = ((EditNameFragment) dialog).getNewFilename(); Log.d(TAG, "name edit dialog dismissed with new name " + newFilename); if (!newFilename.equals(mFile.getFileName())) { FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); if (fdsm.getFileById(mFile.getFileId()) != null) { OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + newFilename); newFile.setCreationTimestamp(mFile.getCreationTimestamp()); newFile.setFileId(mFile.getFileId()); newFile.setFileLength(mFile.getFileLength()); newFile.setKeepInSync(mFile.keepInSync()); newFile.setLastSyncDate(mFile.getLastSyncDate()); newFile.setMimetype(mFile.getMimetype()); newFile.setModificationTimestamp(mFile.getModificationTimestamp()); newFile.setParentId(mFile.getParentId()); boolean localRenameFails = false; if (mFile.isDown()) { File f = new File(mFile.getStoragePath()); Log.e(TAG, f.getAbsolutePath()); localRenameFails = !(f.renameTo(new File(f.getParent() + File.separator + newFilename))); Log.e(TAG, f.getParent() + File.separator + newFilename); newFile.setStoragePath(f.getParent() + File.separator + newFilename); } if (localRenameFails) { Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG); msg.show(); } else { new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start(); boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .showDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); } } } } } else { Log.e( TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName()); } }
public static void write(File file, String s) throws IOException { if (file.getParent() != null) { mkdirs(file.getParent()); } BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.flush(); bw.write(s); bw.close(); }
private static void setPidfile(File cfgFile) { String[] cF = configfile.split("/"); String cFName = cF[cF.length - 1]; cFName = cFName.substring(0, cFName.lastIndexOf(".")); if (null == cfgFile.getParent()) { pidfile = new File(cFName + ".pid"); } else { pidfile = new File(cfgFile.getParent().toString() + '/' + cFName + ".pid"); } cFName = null; cF = null; }
/** * Init the application by making sure the SDK path is available and doing basic parsing of the * SDK. */ private void init() { mSdkCommandLine = new SdkCommandLine(mSdkLog); // We get passed a property for the tools dir String toolsDirProp = System.getProperty(TOOLSDIR); if (toolsDirProp == null) { // for debugging, it's easier to override using the process environment toolsDirProp = System.getenv(TOOLSDIR); } if (toolsDirProp != null) { // got back a level for the SDK folder File tools; if (toolsDirProp.length() > 0) { tools = new File(toolsDirProp); mOsSdkFolder = tools.getParent(); } else { try { tools = new File(".").getCanonicalFile(); mOsSdkFolder = tools.getParent(); } catch (IOException e) { // Will print an error below since mSdkFolder is not defined } } } if (mOsSdkFolder == null) { errorAndExit( "The tools directory property is not set, please make sure you are executing %1$s", SdkConstants.androidCmdName()); } // We might get passed a property for the working directory // Either it is a valid directory and mWorkDir is set to it's absolute canonical value // or mWorkDir remains null. String workDirProp = System.getProperty(WORKDIR); if (workDirProp == null) { workDirProp = System.getenv(WORKDIR); } if (workDirProp != null) { // This should be a valid directory mWorkDir = new File(workDirProp); try { mWorkDir = mWorkDir.getCanonicalFile().getAbsoluteFile(); } catch (IOException e) { mWorkDir = null; } if (mWorkDir == null || !mWorkDir.isDirectory()) { errorAndExit("The working directory does not seem to be valid: '%1$s", workDirProp); } } }
private static String getEclipseHomeLocation(String launcher) { if (launcher == null) return null; File launcherFile = new File(launcher); if (launcherFile.getParent() == null) return null; File launcherDir = new File(launcherFile.getParent()); // check for mac os; the os check is copied from EclipseEnvironmentInfo. String macosx = org.eclipse.osgi.service.environment.Constants.OS_MACOSX; if (macosx.equals(EclipseEnvironmentInfo.getDefault().getOS())) launcherDir = getMacOSEclipsoeHomeLocation(launcherDir); return (launcherDir.exists() && launcherDir.isDirectory()) ? launcherDir.getAbsolutePath() : null; }
public static File changeFileExtension(final File file, String newExt) throws IOException { if (file.isDirectory()) throw new IOException("[" + file + "] is a directory!"); String filename = file.getName(); String origExt = getFileExtension(file.getName()); if (newExt.equals(origExt)) return file; if ("".equals(origExt)) { return new File(file.getParent(), filename + "." + newExt); } else { String f = filename.substring(0, filename.length() - origExt.length()); return new File(file.getParent(), f + newExt); } }
public static File addFilenamePostfix(final File file, String postfix) throws IOException { if (file.isDirectory()) throw new IOException("[" + file + "] is a directory!"); String filename = file.getName(); String origExt = getFileExtension(file.getName()); if ("".equals(origExt)) { return new File(file.getParent(), filename + postfix); } else { String f = filename.substring(0, filename.length() - origExt.length() - 1); String newExt = (origExt.startsWith(".")) ? origExt : "." + origExt; return new File(file.getParent(), f + postfix + newExt); } }