Example usage for java.io File getParent

List of usage examples for java.io File getParent

Introduction

In this page you can find the example usage for java.io File getParent.

Prototype

public String getParent() 

Source Link

Document

Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

Usage

From source file:com.ibm.soatf.tool.Utils.java

/**
 * magic to get the shortened version of the path (8.3 MS-DOS names) on Windows, otherwise, no change
 * <pre></pre>//  w ww . j  a va2s .c o m
 * Example: full path to the <code>file</code> is C:\WORK\Irish Water\projects\trunk\soa_test\IW.600.EBS_M_PCM_SupplierDataVendors\FlowPattern_-_DatabaseToQueueToQueueToDatabase\TestScenarioForVendorSitesOfTypeEBSPCM002\PositiveScenario1SourceToDestination\db\eis_ebs_DatabaseAdapter_XXXIW_MW_PO_VENDOR_SITES_EXT_insert.sql
 * <pre></pre>
 * Returned value: C:\WORK\IRISHW~1\projects\trunk\soa_test\IW600~1.EBS\FLOWPA~1\TESTSC~1\POSITI~1\db\eis_ebs_DatabaseAdapter_XXXIW_MW_PO_VENDOR_SITES_EXT_insert.sql
 * @param file
 * @return shortened path of the <code>file</code> parent and original file name
 */
public static String getOSSafeParentPath(File file) {
    if (!SystemUtils.IS_OS_WINDOWS) {
        return file.getAbsolutePath();
    }
    String shortDir = null;
    try {
        String command = "cmd /c for %I in (\"" + file.getParent() + "\") do %~sI";
        logger.trace("Running cmdline: " + command);
        BufferedReader br = new BufferedReader(
                new InputStreamReader(Runtime.getRuntime().exec(command).getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            int idx = line.indexOf(">");
            if (idx != -1) {
                logger.trace("Got this from the cmdline process: " + line);
                shortDir = line.substring(idx + 1);
                break;
            }
        }
        return shortDir + File.separator + file.getName();
    } catch (IOException e) {
        logger.warn("Could not get the short version of the " + file.getParent() + " directory.", e);
    }
    return null;
}

From source file:eu.optimis.mi.aggregator.util.ConfigManager.java

private static void createDefaultConfigFile(File fileObject) throws IOException {
    log.debug("File " + fileObject.getAbsolutePath() + " didn't exist. Creating one with default values...");

    //Create parent directories.
    log.debug("Creating parent directories.");
    new File(fileObject.getParent()).mkdirs();

    //Create an empty file to copy the contents of the default file.
    log.debug("Creating empty file.");
    new File(fileObject.getAbsolutePath()).createNewFile();

    //Copy file.//  w ww  . j a  v  a  2  s.c o  m
    log.debug("Copying file " + fileObject.getName() + "into path: " + fileObject.getAbsolutePath());
    InputStream streamIn = ConfigManager.class.getResourceAsStream("/" + fileObject.getName());
    FileOutputStream streamOut = new FileOutputStream(fileObject.getAbsolutePath());
    byte[] buf = new byte[8192];
    while (true) {
        int length = streamIn.read(buf);
        if (length < 0) {
            break;
        }
        streamOut.write(buf, 0, length);
    }

    //Close streams after copying.
    try {
        streamIn.close();
    } catch (IOException ex) {
        log.error("Couldn't close input stream");
        log.error(ex.getMessage());
        throw new IOException();
    }
    try {
        streamOut.close();
    } catch (IOException ex) {
        log.error("Couldn't close file output stream");
        log.error(ex.getMessage());
        throw new IOException();
    }
}

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public static KeyStore loadKeyStore(Context context) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, IOException, NoSuchProviderException {
    /*//from   w w  w .  ja va  2 s  .c o  m
     * Original implementation.
    I refer the following sites about the default keystore.
    http://wiki.livedoor.jp/syo1976/d/javassl
    http://d.hatena.ne.jp/Kazzz/20110319/p1
     */
    KeyStore certstore;
    if (Integer.valueOf(Build.VERSION.SDK) >= 14) {
        // load from unified key store
        certstore = KeyStore.getInstance("AndroidCAStore");
        certstore.load(null, null);
    } else {
        certstore = KeyStore.getInstance(KeyStore.getDefaultType());
        certstore.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), null); //load default keystore
    }

    //load self_signed_certificate?
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    final Boolean use_self_signed_certificate = sharedPreferences.getBoolean("use_self_signed_certificate",
            false);
    if (use_self_signed_certificate) {
        final Boolean use_folder = sharedPreferences.getBoolean("use_self_signed_certificate_folder", false);
        final String filename = sharedPreferences.getString("self_signed_certificate_path", "//");
        File myfile = new File(filename);

        if (use_folder) {
            for (File file : new File(myfile.getParent()).listFiles()) {
                if (file.isDirectory())
                    continue;
                FileInputStream stream = new FileInputStream(file);
                X509Certificate cert = MyHttpClient.readPem(stream);
                certstore.setCertificateEntry(file.getName(), cert);
            }
        } else {
            FileInputStream stream = new FileInputStream(myfile);
            X509Certificate cert = MyHttpClient.readPem(stream);
            certstore.setCertificateEntry(myfile.getName(), cert);
        }
        ;
    }
    ;

    return certstore;
}

From source file:com.sunchenbin.store.feilong.core.io.FilenameUtil.java

/**
 *  ??.//from  w  w  w  .  ja  v a 2s. c o m
 * 
 * <pre>
 * {@code
 *   Example 1:
 *      "mp2-product\\mp2-product-impl\\src\\main\\java\\com\\baozun\\mp2\\rpc\\impl\\item\\repo\\package-info.java"
 *      
 *       mp2-product
 * }
 * </pre>
 *
 * @param pathname
 *            ?????? File .,??.
 * @return ,, E:/  E:/
 * @since 1.0.7
 */
public static String getFileTopParentName(String pathname) {
    if (Validator.isNullOrEmpty(pathname)) {
        throw new NullPointerException("pathname can't be null/empty!");
    }

    File file = new File(pathname);
    String parent = file.getParent();

    if (Validator.isNullOrEmpty(parent)) {
        return pathname;
    }

    //
    String fileTopParentName = getFileTopParentName(file);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("pathname:[{}],fileTopParentName:[{}]", pathname, fileTopParentName);
    }
    return fileTopParentName;
}

From source file:eu.optimis.ip.gui.client.resources.ConfigManager.java

private static void createDefaultConfigFile(File fileObject) throws Exception {
    log.debug("File " + fileObject.getAbsolutePath() + " didn't exist. Creating one with default values...");

    //Create parent directories.
    log.debug("Creating parent directories.");
    new File(fileObject.getParent()).mkdirs();

    //Create an empty file to copy the contents of the default file.
    log.debug("Creating empty file.");
    new File(fileObject.getAbsolutePath()).createNewFile();

    //Copy file.//from   w  w w . jav  a 2  s .co m
    log.debug("Copying file " + fileObject.getName());
    InputStream streamIn = ConfigManager.class.getResourceAsStream("/" + fileObject.getName());
    FileOutputStream streamOut = new FileOutputStream(fileObject.getAbsolutePath());
    byte[] buf = new byte[8192];
    while (true) {
        int length = streamIn.read(buf);
        if (length < 0) {
            break;
        }
        streamOut.write(buf, 0, length);
    }

    //Close streams after copying.
    try {
        streamIn.close();
    } catch (IOException ex) {
        log.error("Couldn't close input stream");
        log.error(ex.getMessage());
    }
    try {
        streamOut.close();
    } catch (IOException ex) {
        log.error("Couldn't close file output stream");
        log.error(ex.getMessage());
    }
}

From source file:Main.java

public static boolean isSymlink(File file) throws IOException {
    if (file == null) {
        throw new NullPointerException("File must not be null");
    }/* w  ww.ja  va 2  s .  co m*/
    if (isSystemWindows()) {
        return false;
    }
    File fileInCanonicalDir = null;
    if (file.getParent() == null) {
        fileInCanonicalDir = file;
    } else {
        File canonicalDir = file.getParentFile().getCanonicalFile();
        fileInCanonicalDir = new File(canonicalDir, file.getName());
    }

    return !fileInCanonicalDir.getCanonicalFile().equals(fileInCanonicalDir.getAbsoluteFile());
}

From source file:Main.java

/**
 * Zips a file at a location and places the resulting zip file at the toLocation.
 * <p/>//from  w  w w .  j a v a2  s. co m
 * Example:
 * zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
 * <p/>
 * http://stackoverflow.com/a/14868161
 */
public static void zipFileAtPath(String sourcePath, String toLocation) throws IOException {
    final int BUFFER = 2048;

    File sourceFile = new File(sourcePath);
    FileOutputStream fos = new FileOutputStream(toLocation);
    ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(fos));

    if (sourceFile.isDirectory()) {
        zipSubFolder(zipOut, sourceFile, sourceFile.getParent().length() + 1); // ??

    } else {
        byte data[] = new byte[BUFFER];
        FileInputStream fis = new FileInputStream(sourcePath);
        BufferedInputStream bis = new BufferedInputStream(fis, BUFFER);

        String lastPathComponent = sourcePath.substring(sourcePath.lastIndexOf("/"));

        ZipEntry zipEntry = new ZipEntry(lastPathComponent);
        zipOut.putNextEntry(zipEntry);

        int count;
        while ((count = bis.read(data, 0, BUFFER)) != -1) {
            zipOut.write(data, 0, count);
        }
    }

    zipOut.close();
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java

/**
 * unzip CSAR packge/*from w w w. jav  a  2 s  .  co  m*/
 * @param fileName filePath
 * @return
 */
public static int unzipCSAR(String fileName, String filePath) {
    final int BUFFER = 2048;
    int status = 0;

    try {
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration emu = zipFile.entries();
        int i = 0;
        while (emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) emu.nextElement();
            //read directory as file first,so only need to create directory
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            //Because that is random to read zipfile,maybe the file is read first
            //before the directory is read,so we need to create directory first.
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bos.flush();
            bos.close();
            bis.close();

            if (entry.getName().endsWith(".zip")) {
                File subFile = new File(filePath + entry.getName());
                if (subFile.exists()) {
                    int subStatus = unzipCSAR(filePath + entry.getName(), subFile.getParent() + "/");
                    if (subStatus != 0) {
                        LOG.error("sub file unzip fail!" + subFile.getName());
                        status = Constant.UNZIP_FAIL;
                        return status;
                    }
                }
            }
        }
        status = Constant.UNZIP_SUCCESS;
        zipFile.close();
    } catch (Exception e) {
        status = Constant.UNZIP_FAIL;
        e.printStackTrace();
    }
    return status;
}

From source file:com.nextep.designer.repository.services.impl.RepositoryUpdaterService.java

/**
 * Recursively search for the directory whose parent is the specified export directory in the
 * absolute path of the specified archive file. If no such directory is found, return the parent
 * directory of the specified archive file.
 * /*from w ww  . j a  va2s .  c  om*/
 * @param archiveFile the delivery file for which we need to find the delivery root directory
 * @param exportDir the directory in which the delivery is exported
 * @return the root path of the delivery
 */
private static String getDeliveryRootPath(File archiveFile, File exportDir) {
    String currPath = archiveFile.getParent();
    File parent = archiveFile;
    while (parent != null && !parent.equals(exportDir)) {
        currPath = parent.getAbsolutePath();
        parent = parent.getParentFile();
    }
    return (parent == null ? archiveFile.getParent() : currPath);
}

From source file:ijfx.ui.utils.NamingUtils.java

public static File addSuffix(File original, String suffix) {

    String baseName = FilenameUtils.getBaseName(original.getName());
    String extension = FilenameUtils.getExtension(original.getName());
    String finalName = new StringBuilder().append(baseName).append("_").append(suffix).append(".")
            .append(extension).toString();

    return new File(original.getParent(), finalName);
}