List of usage examples for java.io File getParent
public String getParent()
null
if this pathname does not name a parent directory. From source file:RolloverFileOutputStream.java
private void removeOldFiles() { if (_retainDays > 0) { Calendar retainDate = Calendar.getInstance(); retainDate.add(Calendar.DATE, -_retainDays); int borderYear = retainDate.get(java.util.Calendar.YEAR); int borderMonth = retainDate.get(java.util.Calendar.MONTH) + 1; int borderDay = retainDate.get(java.util.Calendar.DAY_OF_MONTH); File file = new File(_filename); File dir = new File(file.getParent()); String fn = file.getName(); int s = fn.toLowerCase().indexOf(YYYY_MM_DD); if (s < 0) return; String prefix = fn.substring(0, s); String suffix = fn.substring(s + YYYY_MM_DD.length()); String[] logList = dir.list(); for (int i = 0; i < logList.length; i++) { fn = logList[i];//from w ww. j a va 2 s . c om if (fn.startsWith(prefix) && fn.indexOf(suffix, prefix.length()) >= 0) { try { StringTokenizer st = new StringTokenizer( fn.substring(prefix.length(), prefix.length() + YYYY_MM_DD.length()), "_."); int nYear = Integer.parseInt(st.nextToken()); int nMonth = Integer.parseInt(st.nextToken()); int nDay = Integer.parseInt(st.nextToken()); if (nYear < borderYear || (nYear == borderYear && nMonth < borderMonth) || (nYear == borderYear && nMonth == borderMonth && nDay <= borderDay)) { // log.info("Log age "+fn); new File(dir, fn).delete(); } } catch (Exception e) { // if (log.isDebugEnabled()) e.printStackTrace(); } } } } }
From source file:com.opengamma.integration.timeseries.snapshot.RedisLKVFileWriter.java
private void ensureParentDirectory(final File outputFile) { try {/*from w w w .j av a 2 s .c o m*/ s_logger.debug("creating directory {}", outputFile.getParent()); FileUtils.forceMkdir(outputFile.getParentFile()); s_logger.debug("directory created"); } catch (IOException ex) { throw new OpenGammaRuntimeException("Error creating directory " + outputFile.getParent(), ex); } }
From source file:com.liferay.ide.alloy.core.webresources.PortalResourcesProvider.java
@Override public File[] getResources(IWebResourcesContext context) { File[] retval = null;// www . j a v a 2s . c o m final IFile htmlFile = context.getHtmlFile(); final ILiferayProject project = LiferayCore.create(htmlFile.getProject()); if (htmlFile != null && project != null) { final ILiferayPortal portal = project.adapt(ILiferayPortal.class); if (portal != null && ProjectUtil.isPortletProject(htmlFile.getProject())) { final IPath portalDir = portal.getAppServerPortalDir(); if (portalDir != null) { final IPath cssPath = portalDir.append("html/themes/_unstyled/css"); if (cssPath.toFile().exists()) { synchronized (fileCache) { final Collection<File> cachedFiles = fileCache.get(cssPath); if (cachedFiles != null) { retval = cachedFiles.toArray(new File[0]); } else { final Collection<File> files = FileUtils.listFiles(cssPath.toFile(), new String[] { "css", "scss" }, true); final Collection<File> cached = new HashSet<File>(); for (File file : files) { if (file.getName().endsWith("scss")) { final File cachedFile = new File(file.getParent(), ".sass-cache/" + file.getName().replaceAll("scss$", "css")); if (cachedFile.exists()) { cached.add(file); } } } files.removeAll(cached); if (files != null) { retval = files.toArray(new File[0]); } fileCache.put(cssPath, files); } } } } } else if (portal != null && ProjectUtil.isLayoutTplProject(htmlFile.getProject())) { // return the static css resource for layout template names based on the version final String version = portal.getVersion(); try { if (version != null && (version.startsWith("6.0") || version.startsWith("6.1"))) { retval = createLayoutHelperFiles("resources/layouttpl-6.1.css"); } else if (version != null) { retval = createLayoutHelperFiles("resources/layouttpl-6.2.css"); } } catch (IOException e) { AlloyCore.logError("Unable to load layout template helper css files", e); } } } return retval; }
From source file:com.nike.cerberus.operation.dashboard.PublishDashboardOperation.java
private File extractArtifact(final URL artifactUrl) { final File extractionDirectory = Files.createTempDir(); logger.debug("Extracting artifact contents to {}", extractionDirectory.getAbsolutePath()); ArchiveEntry entry;//w w w .j ava 2 s. c om TarArchiveInputStream tarArchiveInputStream = null; try { tarArchiveInputStream = new TarArchiveInputStream( new GzipCompressorInputStream(artifactUrl.openStream())); entry = tarArchiveInputStream.getNextEntry(); while (entry != null) { String entryName = entry.getName(); if (entry.getName().startsWith("./")) { entryName = entry.getName().substring(1); } final File destPath = new File(extractionDirectory, entryName); if (!entry.isDirectory()) { final File fileParentDir = new File(destPath.getParent()); if (!fileParentDir.exists()) { FileUtils.forceMkdir(fileParentDir); } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(destPath); IOUtils.copy(tarArchiveInputStream, fileOutputStream); } finally { IOUtils.closeQuietly(fileOutputStream); } } entry = tarArchiveInputStream.getNextEntry(); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(tarArchiveInputStream); } return extractionDirectory; }
From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java
/** * Unzips a .zip file, removes it from <code>files</code> and adds the extracted files to <code>files</code>. * //w ww . jav a 2 s. co m * @param files the list of files to unzip and the files extracted from the zips * @param fileNames the list of filenames to go along with the list of files */ @SuppressWarnings("PMD.ExcessiveMethodLength") public void unzipFiles(List<File> files, List<String> fileNames) { try { final Pattern p = Pattern.compile("\\.zip$"); int index = 0; for (int i = 0; i < fileNames.size(); i++) { final Matcher m = p.matcher(fileNames.get(i).toLowerCase()); if (m.find()) { final File file = files.get(i); final String fileName = file.getAbsolutePath(); final String directoryPath = file.getParent(); final ZipFile zipFile = new ZipFile(fileName); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final File entryFile = new File(directoryPath + "/" + entry.getName()); final InputStream fileInputStream = zipFile.getInputStream(entry); final FileOutputStream fileOutputStream = new FileOutputStream(entryFile); IOUtils.copy(fileInputStream, fileOutputStream); IOUtils.closeQuietly(fileOutputStream); files.add(entryFile); fileNames.add(entry.getName()); } zipFile.close(); files.remove(index); fileNames.remove(index); } index++; } } catch (final IOException e) { throw new FileAccessException("Couldn't unzip archive.", e); } }
From source file:io.stallion.tools.ExportToHtml.java
@Override public void execute(ServeCommandOptions options) throws Exception { Log.info("EXECUTE EXPORT ACTION!!"); String exportFolder = Settings.instance().getTargetFolder() + "/export-" + DateUtils.formatNow("yyyy-MM-dd-HH-mm-ss"); File export = new File(exportFolder); if (!export.exists()) { export.mkdirs();/*from w w w.j a va2 s.co m*/ } FileUtils.copyDirectory(new File(Settings.instance().getTargetFolder() + "/assets"), new File(exportFolder + "/st-assets")); Set<String> assets = new HashSet<>(); Set<String> allUrlPaths = new HashSet<>(); for (SiteMapItem item : SiteMapController.instance().getAllItems()) { String uri = item.getPermalink(); Log.info("URI {0}", uri); if (!uri.contains("://")) { uri = "http://localhost" + uri; } URL url = new URL(uri); allUrlPaths.add(url.getPath()); } allUrlPaths.addAll(ExporterRegistry.instance().exportAll()); for (String path : allUrlPaths) { Log.info("Export page {0}", path); MockRequest request = new MockRequest(path, "GET"); MockResponse response = new MockResponse(); RequestHandler.instance().handleStallionRequest(request, response); response.getContent(); if (!path.contains(".")) { if (!path.endsWith("/")) { path += "/"; } path += "index.html"; } File file = new File(exportFolder + path); File folder = new File(file.getParent()); if (!folder.isDirectory()) { folder.mkdirs(); } String html = response.getContent(); html = html.replace(Settings.instance().getSiteUrl(), ""); FileUtils.write(file, html, UTF8); assets.addAll(findAssetsInHtml(response.getContent())); } for (String src : assets) { Log.info("Asset src: {0}", src); MockRequest request = new MockRequest(src, "GET"); MockResponse response = new MockResponse(); RequestHandler.instance().handleStallionRequest(request, response); int min = 300; if (response.getContent().length() < 300) { min = response.getContent().length(); } URL url = new URL("http://localhost" + src); File file = new File(exportFolder + url.getPath()); File folder = new File(file.getParent()); if (!folder.isDirectory()) { folder.mkdirs(); } if (url.getPath().endsWith(".js") || url.getPath().endsWith(".css")) { FileUtils.write(file, response.getContent(), UTF8); } else { //ByteArrayOutputStream bos = new ByteArrayOutputStream(); //response.getOutputStream() //bos.writeTo(response.getOutputStream()); //bos.close(); //FileUtils.writeByteArrayToFile(file, response.getContent().getBytes()); } } }
From source file:com.dien.manager.servlet.UploadShpServlet.java
/** * shp//from ww w . ja va2s . co m * * @param pathAndName * @return */ public boolean checkShpFileComplete(String pathAndName, ArrayList<String> msglist) { File shpFile = new File(pathAndName); shpFile.getParent(); if (shpFile.isFile()) { String fNameAll = shpFile.getName(); String fName = fNameAll.substring(0, fNameAll.lastIndexOf(".")); HashMap<String, String> fileList = getShpAllFile(shpFile.getParent(), fName); logger.info(fileList); if (fileList.get(".shp") == null) { msglist.add(".shp"); } if (fileList.get(".shx") == null) { msglist.add(".shx"); } if (fileList.get(".dbf") == null) { msglist.add(".dbf"); } if (fileList.get(".prj") == null) { msglist.add(".prj"); } return msglist.size() > 0 ? false : true; } else { return false; } }
From source file:com.doplgangr.secrecy.FileSystem.Vault.java
public Vault rename(String name) { if (wrongPass) return null; //bye java.io.File folder = new java.io.File(path); java.io.File newFoler = new java.io.File(folder.getParent(), name); try {/*from ww w .j ava 2s .c om*/ FileUtils.copyDirectory(folder, newFoler); } catch (IOException e) { // New Folder should be cleared. Only preserver old folder try { FileUtils.deleteDirectory(newFoler); } catch (IOException ignored) { //ignore } return null; } try { FileUtils.deleteDirectory(folder); } catch (IOException ignored) { //ignored } return new Vault(name, key); }
From source file:daoimplement.resultDao.java
@Override public void write_to_file(String filename) { //Create a file File file = new File(filename); if (!file.exists()) { File citydir = new File(file.getParent()); if (!citydir.exists()) citydir.mkdirs();// w w w. j a v a2 s . c om try { file.createNewFile(); } catch (IOException ex) { Logger.getLogger(resultDao.class.getName()).log(Level.SEVERE, null, ex); } } //Get information from Database List<Results> results = template.loadAll(Results.class); //write to file PrintWriter fout = null; try { fout = new PrintWriter(new BufferedWriter(new FileWriter(file))); for (Results rlst : results) { int student_id = rlst.getStudent().getStudent_id(); int course_id = rlst.getCourse().getCourse_id(); int mark1 = rlst.getMark1(); int mark2 = rlst.getMark2(); fout.println(student_id + "," + course_id + "," + mark1 + "," + mark2); } fout.close(); } catch (IOException ex) { Logger.getLogger(resultDao.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:bio.igm.utils.init.ReduceConstructs.java
public ReduceConstructs(String _path, int _segment_size) throws IOException { this.path = _path; File f = new File(_path); try {//from w ww . java2 s. c o m if (f.isDirectory()) { LOG = new Logging(_path, ReduceConstructs.class.getName()).setup(); } else { LOG = new Logging(f.getParent(), ReduceConstructs.class.getName()).setup(); } } catch (IOException ex) { Logger.getLogger(ReduceConstructs.class.getName()).log(Level.SEVERE, null, ex); } this.segment_size = _segment_size; LOG.info("Reading supplied reference FASTA files.."); constructs = readConstructs("tempConstructs.fa"); can_constructs = readConstructs("tempCan.fa"); LOG.info("Shrinking constructs to specified segment length.."); reduce_constructs("ptes"); reduce_constructs("canonical"); }