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:gov.nih.nci.caintegrator.file.FileManagerImpl.java

/**
 * {@inheritDoc}//from  w ww.  j  av a2 s  .co m
 */
public File renameCnvFile(File cnvFile) throws IOException {
    File newCnvFile = new File(cnvFile.getParent(),
            GisticUtils.CNV_SEGMENT_FILE_PREFIX + System.currentTimeMillis() + ".txt");
    FileUtils.copyFile(cnvFile, newCnvFile);
    cnvFile.delete();
    return newCnvFile;
}

From source file:ste.web.http.velocity.VelocityHandler.java

private String getViewPath(final String uri, final String view) throws HttpException {
    try {/*from  ww  w  . j a  va  2  s.c om*/
        File uriFile = new File(new URI(uri).getPath());
        File viewFile = new File(uriFile.getParent(), new File(viewsFolder, view).getPath());

        return viewFile.getPath();
    } catch (URISyntaxException x) {
        throw new HttpException("URI syntax error for '" + uri + "'", x);
    }
}

From source file:com.doplgangr.secrecy.filesystem.encryption.Vault.java

public Vault rename(String name) {
    if (wrongPass)
        return null; //bye
    File folder = new File(path);
    File newFolder = new File(folder.getParent(), name);
    if (folder.getAbsolutePath().equals(newFolder.getAbsolutePath()))
        return this; //same name, bye
    try {/* ww  w . ja  va  2s .  c o m*/
        org.apache.commons.io.FileUtils.moveDirectory(folder, newFolder);
    } catch (IOException e) {
        return null;
    }
    return VaultHolder.getInstance().createAndRetrieveVault(name, passphrase);
}

From source file:adalid.util.i18n.Mapper.java

private String base(File bundle) {
    String name = bundle.getName();
    String base = _project + FILE_SEPARATOR;
    base += StringUtils.substringAfterLast(bundle.getParent(), join(_project));
    if (name.contains("_")) {
        base = base + FILE_SEPARATOR + StringUtils.substringBefore(name, "_");
    } else {/*from ww w .  j a va 2 s. com*/
        base = base + FILE_SEPARATOR + StringUtils.substringBeforeLast(name, ".");
    }
    return base;
}

From source file:com.roche.sequencing.bioinformatics.common.utils.FileUtil.java

public static String convertToRelativePath(File fromFile, File toFile) {
    StringBuilder relativePathStringBuilder = null;

    String absolutePath = fromFile.getAbsolutePath();
    String relativeTo = toFile.getAbsolutePath();

    if (fromFile.isFile()) {
        absolutePath = fromFile.getParent();
    }/*w  w w  . j av  a2 s .  com*/

    absolutePath = absolutePath.replaceAll("\\\\", "/");
    relativeTo = relativeTo.replaceAll("\\\\", "/");

    if (!absolutePath.equals(relativeTo)) {

        String[] absoluteDirectories = absolutePath.split("/");
        String[] relativeDirectories = relativeTo.split("/");

        // Get the shortest of the two paths
        int length = absoluteDirectories.length < relativeDirectories.length ? absoluteDirectories.length
                : relativeDirectories.length;

        // Use to determine where in the loop we exited
        int lastCommonRoot = -1;
        int index;

        // Find common root
        indexLoop: for (index = 0; index < length; index++) {
            if (absoluteDirectories[index].equals(relativeDirectories[index])) {
                lastCommonRoot = index;
            } else {
                break indexLoop;

            }
        }
        if (lastCommonRoot != -1) {
            // Build up the relative path
            relativePathStringBuilder = new StringBuilder();
            // Add on the ..
            for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) {
                if (absoluteDirectories[index].length() > 0) {
                    relativePathStringBuilder.append("../");
                }
            }
            for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) {
                relativePathStringBuilder.append(relativeDirectories[index] + "/");
            }
            relativePathStringBuilder.append(relativeDirectories[relativeDirectories.length - 1]);
        }
    }
    String returnRelativePath = null;
    if (relativePathStringBuilder != null) {
        returnRelativePath = relativePathStringBuilder.toString();
    } else {
        returnRelativePath = "./" + toFile.getAbsolutePath();
    }
    return returnRelativePath;
}

From source file:jmassivesort.algs.chunks.OneOffChunkReader_LF_ASCII_Test.java

private void checkMergedChunks(int fromChunksNum, int toChunksNum, File src, String outFileName)
        throws IOException {
    for (int i = fromChunksNum; i <= toChunksNum; i++) {
        File out = createTmpFile(src.getParent(), outFileName + "_" + i);

        try (BufferedOutputStream outWr = new BufferedOutputStream(new FileOutputStream(out))) {
            readChunksWriteToOutput(i, src, outWr);

            outWr.close();/*from  ww  w .j  a  v a 2s.  c o m*/
            assertEquals("failed on numChunks=" + i, FileUtils.checksumCRC32(src),
                    FileUtils.checksumCRC32(out));
            FileUtils.forceDelete(out);
        }
    }
}

From source file:Control.HandleAddRestaurant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w  w.  ja  va 2  s  .  c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();
        String[] tempS = null;
        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        path = Paths.tempPath;
        Restaurant temp = new Restaurant();
        String name = null;
        String sepName = Tools.CurrentTime();
        if (ServletFileUpload.isMultipartContent(request)) {
            List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Iterator iter = multiparts.iterator();
            int index = 0;
            tempS = new String[multiparts.size() - 1];
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();

                    String FilePath = path + Paths.logoPathStore + sepName + name;
                    item.write(new File(FilePath));
                } else {
                    String test = item.getFieldName();
                    tempS[index++] = item.getString();
                }
            }
            index = 0;
            temp.ID = tempS[index++];
            temp.name = tempS[index++];
            temp.address = tempS[index++];
            temp.city = tempS[index++];
            temp.state = tempS[index++];
            temp.zipcode = tempS[index++];
            temp.email = tempS[index++];
            temp.phone = tempS[index++];
            temp.monHours = tempS[index++];
            temp.sunHours = tempS[index++];
            temp.minPrice = Double.parseDouble(tempS[index++]);
            temp.fee = Double.parseDouble(tempS[index++]);
            temp.type = Integer.parseInt(tempS[index++]);
            temp.logoImage = Paths.logoPath + sepName + name;
        }

        if (Restaurant.checkExisted(temp.ID, temp.name)) {

            response.sendRedirect("./Admin/AddRestaurant.jsp?index=1");
        } else {
            if (Restaurant.addNewRestaurant(temp)) {
                Tools.updateRestaurants(session);
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=2");
            } else {
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=3");
            }
        }

    } catch (Exception e) {
        response.sendRedirect("./Admin/AddRestaurant.jsp?index=0");
    }
}

From source file:daoimplement.courseDao.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();/* ww  w .j  a  v  a2 s  .com*/

        try {
            file.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(courseDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //Get information from Database

    List<Course> courses = template.loadAll(Course.class);

    //write to file
    PrintWriter fout = null;
    try {
        fout = new PrintWriter(new BufferedWriter(new FileWriter(file)));

        for (Course crs : courses) {
            int course_id = crs.getCourse_id();
            String course_name = crs.getCourse_name();

            fout.println(course_id + "," + course_name);
        }
        fout.close();
    } catch (IOException ex) {
        Logger.getLogger(courseDao.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.seleniumtests.reporter.logger.Snapshot.java

/**
 * Rename HTML and PNG files so that they do not present an uuid
 * New name is <test_name>_<step_idx>_<snapshot_idx>_<step_name>_<uuid>
 * @param testStep/*ww w . j a v  a 2  s. c o m*/
 * @param stepIdx         number of this step
 * @param snapshotIdx   number of this snapshot for this step
 * @param userGivenName   name specified by user, rename to this name
 */
public void rename(final TestStep testStep, final int stepIdx, final int snapshotIdx,
        final String userGivenName) {
    String newBaseName;
    if (userGivenName == null) {
        newBaseName = String.format("%s_%d-%d_%s-",
                StringUtility.replaceOddCharsFromFileName(CommonReporter.getTestName(testStep.getTestResult())),
                stepIdx, snapshotIdx, StringUtility.replaceOddCharsFromFileName(testStep.getName()));
    } else {
        newBaseName = StringUtility.replaceOddCharsFromFileName(userGivenName);
    }

    if (screenshot.getHtmlSourcePath() != null) {
        String oldFullPath = screenshot.getFullHtmlPath();
        String oldPath = screenshot.getHtmlSourcePath();
        File oldFile = new File(oldPath);
        String folderName = "";
        if (oldFile.getParent() != null) {
            folderName = oldFile.getParent().replace(File.separator, "/") + "/";
        }

        String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName());
        newName = newName.substring(0, Math.min(50, newName.length())) + "."
                + FilenameUtils.getExtension(oldFile.getName());

        // if file cannot be moved, go back to old name
        try {
            oldFile = new File(oldFullPath);
            if (SeleniumTestsContextManager.getGlobalContext().getOptimizeReports()) {
                screenshot.setHtmlSourcePath(folderName + newName + ".zip");
                oldFile = FileUtility.createZipArchiveFromFiles(Arrays.asList(oldFile));
            } else {
                screenshot.setHtmlSourcePath(folderName + newName);
            }

            FileUtils.copyFile(oldFile, new File(screenshot.getFullHtmlPath()));
            new File(oldFullPath).delete();

        } catch (IOException e) {
            screenshot.setHtmlSourcePath(oldPath);
        }
    }
    if (screenshot.getImagePath() != null) {
        String oldFullPath = screenshot.getFullImagePath();
        String oldPath = screenshot.getImagePath();
        File oldFile = new File(oldPath);
        String folderName = "";
        if (oldFile.getParent() != null) {
            folderName = oldFile.getParent().replace(File.separator, "/") + "/";
        }

        String newName = newBaseName + FilenameUtils.getBaseName(oldFile.getName());
        newName = newName.substring(0, Math.min(50, newName.length())) + "."
                + FilenameUtils.getExtension(oldFile.getName());
        screenshot.setImagePath(folderName + newName);

        // if file cannot be moved, go back to old name
        try {
            Files.move(Paths.get(oldFullPath), Paths.get(screenshot.getFullImagePath()),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            screenshot.setImagePath(oldPath);
        }
    }
}

From source file:jmassivesort.algs.chunks.SequentialChunkReader_LF_ASCII_Test.java

private void readChunkByChunk(int minChunkSz, int maxChunkSz, int inc, File src, String outFileName)
        throws IOException {
    for (int i = minChunkSz; i <= maxChunkSz; i += inc) {
        File out = createTmpFile(src.getParent(), outFileName + "_" + i);

        try (BufferedOutputStream outWr = new BufferedOutputStream(new FileOutputStream(out))) {
            readAllChunksAndWriteToOutput(i, src, outWr);

            outWr.close();//from ww w  .  j a  v  a2s  . com
            assertEquals("failed on chunkSize=" + i, FileUtils.checksumCRC32(src),
                    FileUtils.checksumCRC32(out));
            FileUtils.forceDelete(out);
        }
    }
}