Example usage for java.io File getPath

List of usage examples for java.io File getPath

Introduction

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

Prototype

public String getPath() 

Source Link

Document

Converts this abstract pathname into a pathname string.

Usage

From source file:com.openkm.applet.Util.java

/**
 * Upload scanned document to OpenKM//  w  w w  .j  a v  a 2s . c o m
 * 
 */
public static String createDocument(String token, String path, String fileName, String fileType, String url,
        List<BufferedImage> images) throws MalformedURLException, IOException {
    log.info("createDocument(" + token + ", " + path + ", " + fileName + ", " + fileType + ", " + url + ", "
            + images + ")");
    File tmpDir = createTempDir();
    File tmpFile = new File(tmpDir, fileName + "." + fileType);
    ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile);
    String response = "";

    try {
        if ("pdf".equals(fileType)) {
            ImageUtils.writePdf(images, ios);
        } else if ("tif".equals(fileType)) {
            ImageUtils.writeTiff(images, ios);
        } else {
            if (!ImageIO.write(images.get(0), fileType, ios)) {
                throw new IOException("Not appropiated writer found!");
            }
        }

        ios.flush();
        ios.close();

        if (token != null) {
            // Send image
            HttpClient client = new DefaultHttpClient();
            MultipartEntity form = new MultipartEntity();
            form.addPart("file", new FileBody(tmpFile));
            form.addPart("path", new StringBody(path, Charset.forName("UTF-8")));
            form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT
            HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token);
            post.setHeader("Cookie", "jsessionid=" + token);
            post.setEntity(form);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = client.execute(post, responseHandler);
        } else {
            // Store in disk
            String home = System.getProperty("user.home");
            File dst = new File(home, tmpFile.getName());
            copyFile(tmpFile, dst);
            response = "Image copied to " + dst.getPath();
        }
    } finally {
        FileUtils.deleteQuietly(tmpDir);
    }

    log.info("createDocument: " + response);
    return response;
}

From source file:edu.unc.lib.dl.util.ZipFileUtil.java

/**
 * Create a temporary directory, unzip the contents of the given zip file to
 * it, and return the directory./*w ww . j a va 2  s. c o  m*/
 * 
 * If anything goes wrong during this process, clean up the temporary
 * directory and throw an exception.
 */
public static File unzipToTemp(InputStream zipStream) throws IOException {
    // get a temporary directory to work with
    File tempDir = File.createTempFile("ingest", null);
    tempDir.delete();
    tempDir.mkdir();
    tempDir.deleteOnExit();
    log.debug("Unzipping to temporary directory: " + tempDir.getPath());
    try {
        unzip(zipStream, tempDir);
        return tempDir;
    } catch (IOException e) {
        // attempt cleanup, then re-throw
        org.apache.commons.io.FileUtils.deleteDirectory(tempDir);
        throw e;
    }
}

From source file:Main.java

private static ArrayList<String> getPathComponents(File file) {
    ArrayList<String> path = new ArrayList<String>();

    while (file != null) {
        File parentFile = file.getParentFile();

        if (parentFile == null) {
            path.add(0, file.getPath());
        } else {/* ww  w  .  ja  v a2 s  . c  o m*/
            path.add(0, file.getName());
        }

        file = parentFile;
    }

    return path;
}

From source file:Main.java

/**
 * zips a directory//from ww  w  .  j  a  va2 s.  c o m
 * @param dir2zip
 * @param zipOut
 * @param zipFileName
 * @throws IOException
 */
private static void zipDir(String dir2zip, ZipOutputStream zipOut, String zipFileName) throws IOException {
    File zipDir = new File(dir2zip);
    // get a listing of the directory content
    String[] dirList = zipDir.list();
    byte[] readBuffer = new byte[2156];
    int bytesIn = 0;
    // loop through dirList, and zip the files
    for (int i = 0; i < dirList.length; i++) {
        File f = new File(zipDir, dirList[i]);
        if (f.isDirectory()) {
            // if the File object is a directory, call this
            // function again to add its content recursively
            String filePath = f.getPath();
            zipDir(filePath, zipOut, zipFileName);
            // loop again
            continue;
        }

        if (f.getName().equals(zipFileName)) {
            continue;
        }
        // if we reached here, the File object f was not a directory
        // create a FileInputStream on top of f
        final InputStream fis = new BufferedInputStream(new FileInputStream(f));
        try {
            ZipEntry anEntry = new ZipEntry(f.getPath().substring(dir2zip.length() + 1));
            // place the zip entry in the ZipOutputStream object
            zipOut.putNextEntry(anEntry);
            // now write the content of the file to the ZipOutputStream
            while ((bytesIn = fis.read(readBuffer)) != -1) {
                zipOut.write(readBuffer, 0, bytesIn);
            }
        } finally {
            // close the Stream
            fis.close();
        }
    }
}

From source file:com.grillecube.engine.renderer.model.json.JSONHelper.java

/**
 * return a String which contains the full file bytes
 * /*from w ww .  j  a va  2s .c  o  m*/
 * @throws IOException
 */
public static String readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("Couldnt read model file. (It doesnt exists: " + file.getPath() + ")");
    }
    if (file.isDirectory()) {
        throw new IOException("Couldnt read model file. (It is a directory!!! " + file.getPath() + ")");
    }
    if (!file.canRead() && !file.setReadable(true)) {
        throw new IOException("Couldnt read model file. (Missing read permissions: " + file.getPath() + ")");
    }

    byte[] encoded = Files.readAllBytes(Paths.get(file.getPath()));
    return (new String(encoded, StandardCharsets.UTF_8));
}

From source file:net.sf.jsignpdf.Signer.java

/**
 * Sign the files/*  w w w  .j a  v  a 2 s . co  m*/
 * 
 * @param anOpts
 */
private static void signFiles(SignerOptionsFromCmdLine anOpts) {
    final SignerLogic tmpLogic = new SignerLogic(anOpts);
    if (ArrayUtils.isEmpty(anOpts.getFiles())) {
        // we've used -lp (loadproperties) parameter
        if (!tmpLogic.signFile()) {
            exit(Constants.EXIT_CODE_ALL_SIG_FAILED);
        }
        return;
    }
    int successCount = 0;
    int failedCount = 0;

    for (final String wildcardPath : anOpts.getFiles()) {
        final File wildcardFile = new File(wildcardPath);

        File[] inputFiles;
        if (StringUtils.containsAny(wildcardFile.getName(), '*', '?')) {
            final File inputFolder = wildcardFile.getAbsoluteFile().getParentFile();
            final FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE,
                    new WildcardFileFilter(wildcardFile.getName()));
            inputFiles = inputFolder.listFiles(fileFilter);
            if (inputFiles == null) {
                continue;
            }
        } else {
            inputFiles = new File[] { wildcardFile };
        }
        for (File inputFile : inputFiles) {
            final String tmpInFile = inputFile.getPath();
            if (!inputFile.canRead()) {
                failedCount++;
                System.err.println(RES.get("file.notReadable", new String[] { tmpInFile }));
                continue;
            }
            anOpts.setInFile(tmpInFile);
            String tmpNameBase = inputFile.getName();
            String tmpSuffix = ".pdf";
            if (StringUtils.endsWithIgnoreCase(tmpNameBase, tmpSuffix)) {
                tmpSuffix = StringUtils.right(tmpNameBase, 4);
                tmpNameBase = StringUtils.left(tmpNameBase, tmpNameBase.length() - 4);
            }
            final StringBuilder tmpName = new StringBuilder(anOpts.getOutPath());
            tmpName.append(anOpts.getOutPrefix());
            tmpName.append(tmpNameBase).append(anOpts.getOutSuffix()).append(tmpSuffix);
            String outFile = anOpts.getOutFile();
            if (outFile == null)
                anOpts.setOutFile(tmpName.toString());
            if (tmpLogic.signFile()) {
                successCount++;
            } else {
                failedCount++;
            }

        }
    }
    if (failedCount > 0) {
        exit(successCount > 0 ? Constants.EXIT_CODE_SOME_SIG_FAILED : Constants.EXIT_CODE_ALL_SIG_FAILED);
    }
}

From source file:FileUtils.java

/**
 * Utility method for copying file//from ww  w.j a v a2s. com
 * @param srcFile - source file
 * @param destFile - destination file
 */
public static void copyFile(File srcFile, File destFile) throws IOException {
    if (!srcFile.getPath().toLowerCase().endsWith(JPG) && !srcFile.getPath().toLowerCase().endsWith(JPEG)) {
        return;
    }
    final InputStream in = new FileInputStream(srcFile);
    final OutputStream out = new FileOutputStream(destFile);
    try {
        long millis = System.currentTimeMillis();
        CRC32 checksum;
        if (VERIFY) {
            checksum = new CRC32();
            checksum.reset();
        }
        final byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = in.read(buffer);
        while (bytesRead >= 0) {
            if (VERIFY) {
                checksum.update(buffer, 0, bytesRead);
            }
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer);
        }
        if (CLOCK) {
            millis = System.currentTimeMillis() - millis;
            System.out.println("Copy file '" + srcFile.getPath() + "' on " + millis / 1000L + " second(s)");
        }
    } catch (IOException e) {
        throw e;
    } finally {
        out.close();
        in.close();
    }
}

From source file:net.nifheim.beelzebu.coins.common.utils.dependencies.DependencyManager.java

public static void loadDependencies(Set<Dependency> dependencies) throws RuntimeException {
    core.getMethods().log("Identified the following dependencies: " + dependencies.toString());

    File libDir = new File(core.getDataFolder(), "lib");
    if (!(libDir.exists() || libDir.mkdirs())) {
        throw new RuntimeException("Unable to create lib dir - " + libDir.getPath());
    }//from   w ww  .j  a v  a 2s.c  om

    // Download files.
    List<File> filesToLoad = new ArrayList<>();
    dependencies.forEach(dependency -> {
        try {
            filesToLoad.add(downloadDependency(libDir, dependency));
        } catch (Exception e) {
            core.getMethods().log("Exception whilst downloading dependency " + dependency.name());
        }
    });

    // Load classes.
    filesToLoad.forEach(file -> {
        try {
            loadJar(file);
        } catch (Throwable t) {
            core.getMethods().log("Failed to load dependency jar " + file.getName());
        }
    });
}

From source file:uk.dsxt.voting.common.utils.PropertiesHelper.java

public static String getResourceString(String name, String encoding) {
    if (name == null || name.isEmpty())
        return "";
    try {// w ww .  ja  v a 2 s.  c om
        final File resourceFile = getConfFile(name);
        if (resourceFile.exists()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(resourceFile.getPath()));
                log.debug("getResourceString. Resource ({}) found: {}", name, resourceFile.getAbsolutePath());
                return new String(encoded, Charset.forName(encoding));
            } catch (IOException e) {
                log.warn("getResourceString. Couldn't read resource from file: {}. error={}",
                        resourceFile.getAbsolutePath(), e.getMessage());
            }
        }

        log.info("getResourceString. Loading resource from jar: {}", name);
        final URL resource = getResource(name);
        if (resource == null) {
            log.warn("getResourceString. Couldn't load resource from jar file: {}.", name);
            return "";
        }
        return IOUtils.toString(resource.openStream(), Charset.forName(encoding));
    } catch (Exception e) {
        log.error("getResourceString. Couldn't read a resource file.", e);
    }
    return "";
}

From source file:S3DataManager.java

public static void zipSource(final String directory, final ZipOutputStream out, final String prefixToTrim)
        throws Exception {
    if (!Paths.get(directory).startsWith(Paths.get(prefixToTrim))) {
        throw new Exception(zipSourceError + "prefixToTrim: " + prefixToTrim + ", directory: " + directory);
    }/*from   w w  w  .j av a  2s.c  om*/

    File dir = new File(directory);
    String[] dirFiles = dir.list();
    if (dirFiles == null) {
        throw new Exception("Invalid directory path provided: " + directory);
    }
    byte[] buffer = new byte[1024];
    int bytesRead;

    for (int i = 0; i < dirFiles.length; i++) {
        File f = new File(dir, dirFiles[i]);
        if (f.isDirectory()) {
            if (f.getName().equals(".git") == false) {
                zipSource(f.getPath() + File.separator, out, prefixToTrim);
            }
        } else {
            FileInputStream inputStream = new FileInputStream(f);
            try {
                String path = trimPrefix(f.getPath(), prefixToTrim);

                ZipEntry entry = new ZipEntry(path);
                out.putNextEntry(entry);
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                inputStream.close();
            }
        }
    }
}