List of usage examples for java.io File getParentFile
public File getParentFile()
null
if this pathname does not name a parent directory. From source file:net.ftb.util.FileUtils.java
public static void backupExtract(String zipLocation, String outputLocation) { Logger.logInfo("Extracting (Backup way)"); byte[] buffer = new byte[1024]; ZipInputStream zis = null;/* w w w. j av a2s . co m*/ ZipEntry ze; try { File folder = new File(outputLocation); if (!folder.exists()) { folder.mkdir(); } zis = new ZipInputStream(new FileInputStream(zipLocation)); ze = zis.getNextEntry(); while (ze != null) { File newFile = new File(outputLocation, ze.getName()); newFile.getParentFile().mkdirs(); if (!ze.isDirectory()) { FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.flush(); fos.close(); } ze = zis.getNextEntry(); } } catch (IOException ex) { Logger.logError("Error while extracting zip", ex); } finally { try { zis.closeEntry(); zis.close(); } catch (IOException e) { } } }
From source file:com.expedia.tesla.compiler.Util.java
/** * Makes any necessary but nonexistent parent directories for a given File. If the parent directory cannot be * created then an IOException is thrown. * <p>/*from w ww . jav a 2s . co m*/ * Workaround for {@code FileUtils.forceMkdirParent} in Apache Commons IO 2.5. * * @param file * file with parent to create, must not be {@code null} * @throws NullPointerException * if the file is {@code null} * @throws IOException * if the parent directory cannot be created * @see <a herf="http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#forceMkdirParent(java.io.File)">FileUtils.forceMkdirParent</a> */ public static void forceMkdirParent(final File file) throws IOException { final File parent = file.getParentFile(); if (parent == null) { return; } FileUtils.forceMkdir(parent); }
From source file:com.skcraft.launcher.persistence.Persistence.java
/** * Read an object from file./*from ww w .j a va2s.co m*/ * * @param file the file * @param cls the class * @param returnNull true to return null if the object could not be loaded * @param <V> the type of class * @return an object */ public static <V> V load(File file, Class<V> cls, boolean returnNull) { ByteSource source = Files.asByteSource(file); ByteSink sink = new MkdirByteSink(Files.asByteSink(file), file.getParentFile()); Scrambled scrambled = cls.getAnnotation(Scrambled.class); if (cls.getAnnotation(Scrambled.class) != null) { source = new ScramblingSourceFilter(source, scrambled.value()); sink = new ScramblingSinkFilter(sink, scrambled.value()); } V object = read(source, cls, returnNull); Persistence.bind(object, sink); return object; }
From source file:com.taobao.diamond.common.Constants.java
/** ?-D > env > diamond.properties */ public static void init() { File diamondFile = new File(System.getProperty("user.home"), "diamond/ServerAddress"); if (!diamondFile.exists()) { diamondFile.getParentFile().mkdirs(); try (OutputStream out = new FileOutputStream(diamondFile)) { out.write("localhost".getBytes()); } catch (IOException e) { throw new IllegalStateException(diamondFile.toString(), e); }/*from w w w . ja va 2 s .c o m*/ } List<Field> fields = new ArrayList<>(); for (Field field : Constants.class.getDeclaredFields()) { if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { fields.add(field); } } Properties props = new Properties(); { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) cl = Constants.class.getClassLoader(); try (InputStream in = cl.getResourceAsStream("diamond.properties")) { if (in != null) props.load(in); } catch (IOException e) { log.warn("load diamond.properties", e); } } props.putAll(System.getenv()); props.putAll(System.getProperties()); Map<String, Object> old = new HashMap<>(); try { for (Field field : fields) { if (!props.containsKey(field.getName())) continue; old.put(field.getName(), field.get(Constants.class)); String value = props.getProperty(field.getName()); Class<?> clazz = field.getType(); if (String.class.equals(clazz)) { field.set(Constraints.class, value); } else if (int.class.equals(clazz)) { if (value != null) { field.set(Constraints.class, Integer.parseInt(value)); } } else { throw new IllegalArgumentException(field + " " + value + " ?"); } } } catch (IllegalAccessException e) { throw new IllegalStateException(e); } setValue(old, "CONFIG_HTTP_URI_FILE", "HTTP_URI_FILE"); setValue(old, "HTTP_URI_LOGIN", "HTTP_URI_FILE"); setValue(old, "DAILY_DOMAINNAME", "DEFAULT_DOMAINNAME"); }
From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java
private static void loadConfig() { boolean read = false; File f = CONFIG_FILE; if (!f.exists()) { read = true;// www. j ava2 s . co m try { f.getParentFile().mkdirs(); f.createNewFile(); java.nio.file.Files.setPosixFilePermissions(Paths.get(f.toURI()), PosixFilePermissions.fromString("rw-------")); } catch (IOException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); System.err.println("Error writing empty config.yml!"); } } Map<String, Object> config; if (read) { Console console = System.console(); console.printf("Nick: \n->"); nick = console.readLine(); console.printf("\nPassword: \n-|"); pass = new String(console.readPassword()); console.printf("\nServer: \n->"); server = console.readLine(); console.printf("\nChannels: (ex: #java,#linux,#gnome)\n->"); channels = Arrays.asList(console.readLine().split(",")); System.out.println("Fetching max XKCD..."); maxXKCD = fetchMaxXKCD(); System.out.println("Fetched."); cachedUTC = System.currentTimeMillis(); dadLeaveTimes = new HashMap<>(); noVoiceNicks = new HashSet<>(); writeConfig(); System.out.println("Wrote config to file: " + CONFIG_FILE.getAbsolutePath()); } else { try (FileInputStream fis = new FileInputStream(f)) { Yaml y = new Yaml(); config = y.loadAs(fis, Map.class); } catch (IOException ex) { Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex); System.err.println("Error parsing config!"); return; } nick = (String) config.get("nick"); pass = (String) config.get("password"); server = (String) config.get("server"); channels = (List<String>) config.get("channels"); maxXKCD = (Integer) config.get("cachedMaxXKCD"); cachedUTC = (Long) config.get("cachedUTC"); noVoiceNicks = (Set<String>) config.get("noVoiceNicks"); masters = (Set<String>) config.get("masters"); if (masters == null) { masters = new HashSet<>(); masters.add("Everdras"); } if (noVoiceNicks == null) noVoiceNicks = new HashSet<>(); noVoiceNicks.stream().forEach((s) -> System.out.println("Loaded novoice nick: " + s)); masters.stream().forEach((s) -> System.out.println("Loaded master nick: " + s)); if (checkXKCDUpdate()) writeConfig(); else System.out.println("Loaded cached XKCD."); Map<String, Object> serialDadLeaveTimes = (Map<String, Object>) config.get("dadLeaveTimes"); dadLeaveTimes = new HashMap<>(); if (serialDadLeaveTimes != null) serialDadLeaveTimes.keySet().stream().forEach((time) -> { dadLeaveTimes.put(LocalDate.parse(time), LocalTime.parse((String) serialDadLeaveTimes.get(time))); }); } }
From source file:Main.java
private static File getRelativePath(final File file, final File relativeToThis, final String relativeInitial) { File parent = file; String relative = null;/*from w ww.j a v a 2 s . c o m*/ while (parent != null) { if (parent.equals(relativeToThis)) { return new File(relativeInitial + (relative == null ? "." : relative)); } relative = parent.getName() + (relative == null ? "" : "/" + relative); parent = parent.getParentFile(); } final File toParent = relativeToThis.getParentFile(); if (toParent == null) return null; else return getRelativePath(file, toParent, "../" + relativeInitial); }
From source file:com.pieframework.runtime.utils.Zipper.java
public static void unzip(String zipFile, String toDir) throws ZipException, IOException { int BUFFER = 2048; File file = new File(zipFile); ZipFile zip = new ZipFile(file); String newPath = toDir;//from www.j av a2s . co m File toDirectory = new File(newPath); if (!toDirectory.exists()) { toDirectory.mkdir(); } Enumeration zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, FilenameUtils.separatorsToSystem(currentEntry)); //System.out.println(currentEntry); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } zip.close(); }
From source file:com.smart.common.officeFile.CSVUtils.java
/** * * @param exportData ?/*w ww.ja v a 2s.c o m*/ * @param rowMapper ?? * @param outPutPath * @param filename ?? * @return */ public static File createCSVFile(List exportData, LinkedHashMap rowMapper, String outPutPath, String filename) { File csvFile = null; BufferedWriter csvFileOutputStream = null; try { csvFile = new File(outPutPath + filename + ".csv"); // csvFile.getParentFile().mkdir(); File parent = csvFile.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } csvFile.createNewFile(); // GB2312?"," csvFileOutputStream = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024); // for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\""); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } csvFileOutputStream.newLine(); // for (Iterator iterator = exportData.iterator(); iterator.hasNext();) { LinkedHashMap row = (LinkedHashMap) iterator.next(); System.out.println(row); for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); // System.out.println(BeanUtils.getProperty(row, propertyEntry.getKey().toString())); csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\""); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } // for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) { // java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); // System.out.println(BeanUtils.getProperty(row, propertyEntry.getKey().toString())); // csvFileOutputStream.write("\"" // + BeanUtils.getProperty(row, propertyEntry.getKey().toString()) + "\""); // if (propertyIterator.hasNext()) { // csvFileOutputStream.write(","); // } // } if (iterator.hasNext()) { csvFileOutputStream.newLine(); } } csvFileOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { csvFileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return csvFile; }
From source file:androidimporter.AndroidImporter.java
/** * @param args the command line arguments *///from w w w . j ava 2 s . com public static void main_old(String[] args) throws Exception { // TODO code application logic here JavaSEPort.setShowEDTViolationStacks(false); JavaSEPort.setShowEDTWarnings(false); JFrame frm = new JFrame("Placeholder"); frm.setVisible(false); Display.init(frm.getContentPane()); File k9MailResFolder = new File("test_inputs/k9mail/src/main/res"); File k9MailLayout = new File(k9MailResFolder, "layout"); File resDest = new File(new File("AndroidImporterTestBed/src"), "theme.res"); JavaSEPort.setBaseResourceDir(resDest.getParentFile()); for (File folder : k9MailResFolder.listFiles()) { if (!folder.getName().startsWith("values")) { continue; } String locale = "en"; if (folder.getName().contains("-")) { locale = folder.getName().substring(folder.getName().indexOf("-") + 1); } File stringsFile = new File(folder, "strings.xml"); if (!stringsFile.exists()) { continue; } AndroidStringImporter.importStrings(stringsFile, resDest, locale, null); } for (File input : k9MailLayout.listFiles()) { if (input.getName().endsWith(".xml")) { String baseName = ucFirst(toCamelCase(input.getName().replaceFirst("\\.xml$", ""))); String guiName = baseName + ".gui"; String javaName = baseName + ".java"; File dest = new File(new File("AndroidImporterTestBed/res/guibuilder/com/codename1/k9tests"), guiName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } File javaDest = new File(new File("AndroidImporterTestBed/src/com/codename1/k9tests"), javaName); if (!javaDest.getParentFile().exists()) { javaDest.getParentFile().mkdirs(); } AndroidLayoutImporter.importLayout(input, dest, resDest, null); /* GenerateGuiSources gen = new GenerateGuiSources(); gen.setGuiDir(new File("AndroidImporterTestBed/res/guibuilder")); gen.setSrcDir(new File("AndroidImporterTestBed/src")); String javaSource = gen.generateFullSource(dest); try (FileOutputStream fos = new FileOutputStream(javaDest)) { fos.write(javaSource.getBytes("UTF-8")); }*/ } } Runtime.getRuntime().exec(new String[] { "/usr/local/apache-ant/bin/ant", "init" }, new String[] {}, resDest.getParentFile().getParentFile()); System.exit(0); //AndroidLayoutImporter.importLayout(new File(args[0]), new File(args[1])); }
From source file:com.codenvy.commons.lang.TarUtils.java
public static void tarFiles(File tar, long modTime, File... files) throws IOException { try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream( new BufferedOutputStream(new FileOutputStream(tar)))) { tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); for (File f : files) { if (f.isDirectory()) { addDirectoryEntry(tarOut, f.getName(), f, modTime); final String parentPath = f.getParentFile().getAbsolutePath(); addDirectoryRecursively(tarOut, parentPath, f, modTime, IoUtil.ANY_FILTER); } else if (f.isFile()) { addFileEntry(tarOut, f.getName(), f, modTime); }/*from w ww .j a v a 2s.c o m*/ } } }