Example usage for java.io File getAbsoluteFile

List of usage examples for java.io File getAbsoluteFile

Introduction

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

Prototype

public File getAbsoluteFile() 

Source Link

Document

Returns the absolute form of this abstract pathname.

Usage

From source file:com.sciaps.utils.Util.java

public static String getIPAddress() {
    String address = null;//from   w w  w.  j ava2 s .c o  m

    try {
        File file = new File(Constants.LIBZ_URL_FILE_NAME);

        FileReader fr = new FileReader(file.getAbsoluteFile());
        BufferedReader br = new BufferedReader(fr);

        String line = br.readLine();
        line = line.trim();
        br.close();

        // Making sure the ip address is valid
        if (com.sciaps.utils.Util.validateIPAddress(line)) {
            address = line;
        }

    } catch (FileNotFoundException ex) {

    } catch (IOException ex) {

    }

    return address;
}

From source file:com.csipsimple.utils.SipProfileJson.java

/**
 * Save current sip configuration//  ww w  .j  av a  2  s.co m
 * @param ctxt
 * @return
 */
public static boolean saveSipConfiguration(Context ctxt) {
    File dir = PreferencesWrapper.getConfigFolder();
    if (dir != null) {
        Date d = new Date();
        File file = new File(dir.getAbsoluteFile() + File.separator + "backup_"
                + DateFormat.format("MM-dd-yy_kkmmss", d) + ".json");
        Log.d(THIS_FILE, "Out dir " + file.getAbsolutePath());

        JSONObject configChain = new JSONObject();
        try {
            configChain.put(KEY_ACCOUNTS, serializeSipProfiles(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }
        try {
            configChain.put(KEY_SETTINGS, serializeSipSettings(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }

        try {
            // Create file
            FileWriter fstream = new FileWriter(file.getAbsoluteFile());
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(configChain.toString(2));
            // Close the output stream
            out.close();
            return true;
        } catch (Exception e) {
            // Catch exception if any
            Log.e(THIS_FILE, "Impossible to save config to disk", e);
            return false;
        }
    }
    return false;
}

From source file:com.chigix.autosftp.Application.java

public static void watchDir(Path dir) throws Exception {
    // The monitor will perform polling on the folder every 5 seconds
    final long pollingInterval = 5 * 1000;

    File folder = dir.toFile();/*  w w  w  . j  a  v a  2 s. c o m*/

    if (!folder.exists()) {
        // Test to see if monitored folder exists
        throw new FileNotFoundException("Directory not found: " + dir);
    }

    FileAlterationObserver observer = new FileAlterationObserver(folder);
    FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
    FileAlterationListener listener = new FileAlterationListenerAdaptor() {
        // Is triggered when a file is created in the monitored folder
        @Override
        public void onFileCreate(File file) {
            Path relativePath = localPath.toAbsolutePath().normalize()
                    .relativize(file.getAbsoluteFile().toPath().normalize());
            System.out.println("File created: " + relativePath);
            final String destPath = remotePath.resolve(relativePath).normalize().toString().replace('\\', '/');
            ArrayList<String> lackDirs = new ArrayList<>();
            String tmpParentPath = destPath;
            while (!tmpParentPath.equals("/") && !tmpParentPath.equals("\\")) {
                tmpParentPath = new File(tmpParentPath).getParentFile().toPath().toString().replace('\\', '/');
                try {
                    sftpChannel.cd(tmpParentPath);
                } catch (SftpException ex) {
                    if (ex.id == SSH_FX_NO_SUCH_FILE) {
                        lackDirs.add(tmpParentPath);
                        continue;
                    }
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                    return;
                }
                break;
            }
            for (int i = lackDirs.size() - 1; i > -1; i--) {
                try {
                    sftpChannel.mkdir(lackDirs.get(i));
                } catch (SftpException ex) {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                    System.err.println(destPath + " Creating Fail.");
                    return;
                }
            }
            InputStream fi = null;
            try {
                fi = new FileInputStream(file);
                sftpChannel.put(fi, destPath, 644);
            } catch (FileNotFoundException ex) {
                System.out.println("File: " + file.getAbsolutePath() + " not exists.");
                return;
            } catch (SftpException ex) {
                Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                return;
            } finally {
                if (fi != null) {
                    try {
                        fi.close();
                    } catch (IOException ex) {
                    }
                }
            }
            System.out.println("File Uploaded: " + destPath);
        }

        // Is triggered when a file is deleted from the monitored folder
        @Override
        public void onFileDelete(File file) {
            if (file.exists()) {
                return;
            }
            Path relativePath = localPath.toAbsolutePath().normalize()
                    .relativize(file.getAbsoluteFile().toPath().normalize());
            System.out.println("File Deleted: " + relativePath);
            final String destPath = remotePath.resolve(relativePath).normalize().toString().replace('\\', '/');
            try {
                sftpChannel.rm(destPath);
            } catch (SftpException ex) {
                if (ex.id == SSH_FX_NO_SUCH_FILE) {
                } else {
                    Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            System.out.println("Remote Deleted: " + relativePath);
        }

        @Override
        public void onFileChange(File file) {
            this.onFileCreate(file);
        }

    };

    observer.addListener(listener);
    monitor.addObserver(observer);
    monitor.start();
}

From source file:test.org.tradex.camel.TestCaseAppContextBuilder.java

/**
 * Builds an application context reading the file from the passed path
 * @param path The path of the app context xml
 * @return the built app context/*from   w  w  w. j a  v  a  2s.c o  m*/
 */
public static GenericXmlApplicationContext buildFor(String path) {
    if (path == null)
        throw new IllegalArgumentException("Passed path was null", new Throwable());
    File springXml = new File(path);
    if (!springXml.canRead()) {
        throw new RuntimeException("Failed to read Spring XML file at [" + springXml + "]", new Throwable());
    }
    try {
        return service(new GenericXmlApplicationContext(
                new FileSystemResource[] { new FileSystemResource(springXml.getAbsoluteFile()) }));
    } catch (Throwable t) {
        LOG.fatal("Failed to boot app context", t);
        throw new RuntimeException("Failed to boot app context", t);
    }
}

From source file:edu.usc.polar.CompositeNERAgreementParser.java

public static void dir(String path, String[] args) {
    try {//from  w w w .  j  a  v  a2s  .  c  o m

        File root = new File(path);
        if (root.isFile()) {

            if (counter >= 1000 || file == null) {
                counter = 0;
                jsonCount++;
                file = new File(
                        "C:\\Users\\Snehal\\Documents\\tikaSimilarityTestSet\\CompositeNER\\CompositeNER_"
                                + jsonCount + ".json");
                if (jsonFile != null) {
                    jsonFile.write("{\"CompositeNER\":");
                    jsonFile.write(jsonArray.toJSONString());
                    jsonFile.write("}");
                    //System.out.println(jsonArray.toJSONString());
                    jsonFile.close();
                }
                jsonFile = new FileWriter(file);
                jsonArray = new JSONArray();
            }

            if (!root.getName().equals((".DS_Store"))) {
                CompositeNER(root.getAbsolutePath(), args);
                counter++;
            }
        } else {
            File[] list = root.listFiles();
            if (list == null) {
                return;
            }
            for (File f : list) {
                if (f.isDirectory()) {
                    dir(f.getAbsolutePath(), args);
                    System.out.println("Dir:" + f.getAbsoluteFile());
                } else {
                    if (counter >= 1000 || file == null) {
                        counter = 0;
                        jsonCount++;
                        file = new File(
                                "C:\\Users\\Snehal\\Documents\\tikaSimilarityTestSet\\CompositeNER\\CompositeNER_"
                                        + jsonCount + ".json");
                        // System.out.print("check"+jsonArray.toJSONString());
                        if (jsonFile != null) {
                            jsonFile.write("{\"CompositeNER\":");
                            jsonFile.write(jsonArray.toJSONString());
                            jsonFile.write("}");
                            //System.out.println(jsonArray.toJSONString());
                            jsonFile.close();
                        }
                        jsonFile = new FileWriter(file);
                        jsonArray = new JSONArray();
                    }

                    if (!f.getName().equals((".DS_Store"))) {
                        CompositeNER(f.getAbsolutePath(), args);
                        counter++;
                        // add json   
                    }
                }
            }
        }
    } catch (Exception e) {
        e.toString();

    }
}

From source file:com.smartmarmot.dbforbix.DBforBix.java

public static void writePid(String _pidfile) throws Exception {
    RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
    String pid = rmxb.getName();/*from w  w  w. j a v  a  2  s  . c  om*/
    try {

        File target = new File(_pidfile);

        File newTarget = new File(target.getAbsoluteFile().getCanonicalPath());
        target = null;

        if (newTarget.exists()) {
            boolean success = newTarget.delete();
            if (!success) {
                DBforBix.LOG.log(Level.ERROR, "Delete: deletion failed " + newTarget.getAbsolutePath());
            }
        }
        if (!newTarget.exists()) {
            FileOutputStream fout = new FileOutputStream(newTarget);
            new PrintStream(fout).print(pid);
            fout.close();
        }

    } catch (IOException e) {
        DBforBix.LOG.log(Level.ERROR, "Unable to write to file " + _pidfile + " error:" + e);
    }
}

From source file:it.iit.genomics.cru.bridges.liftover.ws.LiftOverRun.java

public static Mapping runLiftOver(String genome, String fromAssembly, String toAssembly, String chromosome,
        int start, int end) {

    String liftOverCommand = RESOURCE_BUNDLE.getString("liftOverCommand");

    String liftOverPath = RESOURCE_BUNDLE.getString("liftOverPath");

    String mapChainDir = RESOURCE_BUNDLE.getString("mapChainDir");

    String tmpDir = RESOURCE_BUNDLE.getString("tmpDir");

    Mapping mapping = null;/*from w  w  w  .  j  a  va 2s  .com*/

    Runtime r = Runtime.getRuntime();

    String rootFilename = String.format("%s", RandomStringUtils.randomAlphanumeric(8));

    String inputFilename = rootFilename + "-" + fromAssembly + ".bed";
    String outputFilename = rootFilename + "-" + toAssembly + ".bed";
    String unmappedFilename = rootFilename + "-" + "unmapped.bed";

    String mapChain = fromAssembly.toLowerCase() + "To" + toAssembly.toUpperCase().charAt(0)
            + toAssembly.toLowerCase().substring(1) + ".over.chain.gz";

    try {

        File tmpDirFile = new File(tmpDir);

        // if the directory does not exist, create it
        if (false == tmpDirFile.exists()) {
            System.out.println("creating directory: " + tmpDir);
            boolean result = tmpDirFile.mkdir();

            if (result) {
                System.out.println("DIR created");
            }
        }

        // Write input bed file
        File inputFile = new File(tmpDir + inputFilename);
        // if file doesnt exists, then create it
        if (!inputFile.exists()) {
            inputFile.createNewFile();
        }

        FileWriter fw = new FileWriter(inputFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(chromosome + "\t" + start + "\t" + end + "\n");
        bw.close();

        String commandArgs = String.format("%s %s %s %s %s", liftOverPath + "/" + liftOverCommand,
                tmpDir + inputFilename, mapChainDir + mapChain, tmpDir + outputFilename,
                tmpDir + unmappedFilename);
        System.out.println(commandArgs);

        Process p = r.exec(commandArgs);

        p.waitFor();

        BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";

        while ((line = b.readLine()) != null) {
            System.out.println(line);
        }
        b.close();

        b = new BufferedReader(new FileReader(tmpDir + outputFilename));

        while ((line = b.readLine()) != null) {
            String[] cells = line.split("\t");
            String newChromosome = cells[0];
            int newStart = Integer.parseInt(cells[1]);
            int newEnd = Integer.parseInt(cells[2]);
            mapping = new Mapping(genome, toAssembly, newChromosome, newStart, newEnd);
        }
        b.close();

        // delete
        File delete = new File(tmpDir + inputFilename);
        delete.delete();

        delete = new File(tmpDir + outputFilename);
        delete.delete();

        delete = new File(tmpDir + unmappedFilename);
        delete.delete();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return mapping;
}

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

/**
 * Sign the files/*from  w  w w.  ja  va 2 s  .c o  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:abfab3d.shapejs.Project.java

private static void extractZip(String zipFile, String outputFolder, Map<String, String> sceneFiles,
        List<String> resources) {
    byte[] buffer = new byte[1024];

    try {//from   ww w  .  j  a va 2  s .  c o m
        //create output directory is not exists
        File folder = new File(outputFolder);
        if (!folder.exists()) {
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            // Ignore directories
            if (ze.isDirectory())
                continue;

            String fileName = ze.getName();
            File newFile = new File(outputFolder + File.separator + fileName);
            System.out.println("file unzip : " + newFile.getAbsoluteFile());

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            // Save path to the script and parameters files
            if (fileName.endsWith(".json")) {
                sceneFiles.put("paramFile", newFile.getAbsolutePath());
            } else if (fileName.endsWith(".js")) {
                sceneFiles.put("scriptFile", newFile.getAbsolutePath());
            } else {
                resources.add(newFile.getAbsolutePath());
            }

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java

private static void prepareDestination(File destination) throws IOException {
    if (destination.exists()) {
        FileUtils.forceDelete(destination);
    }//from w  w  w .  j  av  a  2s .c om
    File parent = destination.getAbsoluteFile().getParentFile();
    if (parent.mkdirs() == false && parent.exists() == false) {
        throw new IOException(MessageFormat.format("failed to create directory: {0}", destination));
    }
}