Java Code Examples for java.io.File#getAbsoluteFile()

The following examples show how to use java.io.File#getAbsoluteFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MostradorDeCodigo.java    From brModelo with GNU General Public License v3.0 6 votes vote down vote up
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
    String pat = Aplicacao.getDiagramaSelecionado().getArquivo();
    if (pat != null && !pat.isEmpty()) {
        pat = (new File(pat)).getParentFile().getAbsolutePath() + File.separator +  Aplicacao.getDiagramaSelecionado().getNome() + ".sql";
    }
    File arq = util.Dialogos.ShowDlgSaveAsAny(this.getRootPane(), pat);
    if (arq == null) {
        return;
    }
    
    if (arq.exists()) {
        if (util.Dialogos.ShowMessageConfirm(getRootPane(), Editor.fromConfiguracao.getValor("Controler.MSG_QUESTION_REWRITE")) != JOptionPane.YES_OPTION) {
            return;
        }
    }
    try {
        PrintWriter out = new PrintWriter(arq.getAbsoluteFile());
        out.print(buffer);
        out.close();
    } catch (IOException iOException) {
        util.BrLogger.Logger("ERROR_DIAGRAMA_SAVE_ANY", iOException.getMessage());
    }
}
 
Example 2
Source File: PlayerView.java    From qplayer-sdk with MIT License 6 votes vote down vote up
public int OnImage (byte[] pData, int nSize) {
	try{
		File parent_path = Environment.getExternalStorageDirectory();
		File dir = new File(parent_path.getAbsoluteFile(), "CaptureVideo");
		dir.mkdir();
		File file = new File(dir.getAbsoluteFile(), "0001.jpg");
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(pData, 0, pData.length);
		fos.flush();
		fos.close();
	} catch(Exception e){
		e.printStackTrace();
	}
	return 0;
}
 
Example 3
Source File: OCRTextRecognition.java    From NeurophFramework with Apache License 2.0 6 votes vote down vote up
/**
 * save the recognized text to the file specified earlier in location folder
 */
public void saveText() {
    try {
        File file = new File(recognizedTextPath);
        if (!file.exists()) {
            file.createNewFile();
        }
        String[] lines = text.split("\n");
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        for (String line : lines) {
            bw.write(line);
            bw.newLine();
        }
        bw.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}
 
Example 4
Source File: IJProjectCleaner.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
protected void compute() {
  File[] files = directory.listFiles(filenameFilter);
  if (files == null) {
    return;
  }

  for (File file : files) {
    file = file.getAbsoluteFile();
    if (filesToKeep.contains(file)) {
      LOG.warn("Skipping " + file);
      continue;
    }

    LOG.warn("Deleting " + file);
    if (!file.delete()) {
      LOG.warn("Unable to delete " + file);
    }
  }
}
 
Example 5
Source File: LocalFilesystem.java    From L.TileLayer.Cordova with MIT License 5 votes vote down vote up
/**
 * Copy a directory
 *
 * @param srcDir directory to be copied
 * @param destinationDir destination to be copied to
 * @return a DirectoryEntry object
 * @throws JSONException
 * @throws IOException
 * @throws NoModificationAllowedException
 * @throws InvalidModificationException
 */
private JSONObject copyDirectory(File srcDir, File destinationDir) throws JSONException, IOException, NoModificationAllowedException, InvalidModificationException {
    // Renaming a file to an existing directory should fail
    if (destinationDir.exists() && destinationDir.isFile()) {
        throw new InvalidModificationException("Can't rename a file to a directory");
    }

    // Check to make sure we are not copying the directory into itself
    if (isCopyOnItself(srcDir.getAbsolutePath(), destinationDir.getAbsolutePath())) {
        throw new InvalidModificationException("Can't copy itself into itself");
    }

    // See if the destination directory exists. If not create it.
    if (!destinationDir.exists()) {
        if (!destinationDir.mkdir()) {
            // If we can't create the directory then fail
            throw new NoModificationAllowedException("Couldn't create the destination directory");
        }
    }
    

    for (File file : srcDir.listFiles()) {
        File destination = new File(destinationDir.getAbsoluteFile() + File.separator + file.getName());
        if (file.isDirectory()) {
            copyDirectory(file, destination);
        } else {
            copyFile(file, destination);
        }
    }

    return makeEntryForFile(destinationDir);
}
 
Example 6
Source File: DefaultPackageReader.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
private ConfigValues loadConfigValues(File file) {
	ConfigValues configValues = new ConfigValues();
	try {
		configValues.setRaw(new String(Files.readAllBytes(file.toPath()), "UTF-8"));
	}
	catch (IOException e) {
		throw new SkipperException("Could read values file " + file.getAbsoluteFile(), e);
	}
	return configValues;
}
 
Example 7
Source File: DataFile.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve a path and always return an absolute path (e.g. relative to 'currentDir')
 */
public static File resolveLocalPath(String fileName, String currentDir) {
	if (fileName.toLowerCase().startsWith(PROTOCOL_FILE)) fileName = fileName.substring(PROTOCOL_FILE.length());
	File f = new File(fileName);

	// If fileName is an absolute path, we just return the appropriate file
	if (currentDir == null) return f;
	if (f.toPath().isAbsolute()) return f.getAbsoluteFile();

	// Resolve against 'currentDir'
	return new File(currentDir, fileName).getAbsoluteFile();
}
 
Example 8
Source File: AquaFileChooserUI.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds the directory to the model and sets it to be selected,
 * additionally clears out the previous selected directory and
 * the paths leading up to it, if any.
 */
void addItem(final File directory) {
    if (directory == null) { return; }
    if (fSelectedDirectory != null) {
        removeSelectedDirectory();
    }

    // create File instances of each directory leading up to the top
    File f = directory.getAbsoluteFile();
    final Vector<File> path = new Vector<File>(10);
    while (f.getParent() != null) {
        path.addElement(f);
        f = getFileChooser().getFileSystemView().createFileObject(f.getParent());
    };

    // Add root file (the desktop) to the model
    final File[] roots = getFileChooser().getFileSystemView().getRoots();
    for (final File element : roots) {
        path.addElement(element);
    }
    fPathCount = path.size();

    // insert all the path fDirectories leading up to the
    // selected directory in reverse order (current directory at top)
    for (int i = 0; i < path.size(); i++) {
        fDirectories.addElement(path.elementAt(i));
    }

    setSelectedItem(fDirectories.elementAt(0));

    // dump();
}
 
Example 9
Source File: AquaFileChooserUI.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds the directory to the model and sets it to be selected,
 * additionally clears out the previous selected directory and
 * the paths leading up to it, if any.
 */
void addItem(final File directory) {
    if (directory == null) { return; }
    if (fSelectedDirectory != null) {
        removeSelectedDirectory();
    }

    // create File instances of each directory leading up to the top
    File f = directory.getAbsoluteFile();
    final Vector<File> path = new Vector<File>(10);
    while (f.getParent() != null) {
        path.addElement(f);
        f = getFileChooser().getFileSystemView().createFileObject(f.getParent());
    };

    // Add root file (the desktop) to the model
    final File[] roots = getFileChooser().getFileSystemView().getRoots();
    for (final File element : roots) {
        path.addElement(element);
    }
    fPathCount = path.size();

    // insert all the path fDirectories leading up to the
    // selected directory in reverse order (current directory at top)
    for (int i = 0; i < path.size(); i++) {
        fDirectories.addElement(path.elementAt(i));
    }

    setSelectedItem(fDirectories.elementAt(0));

    // dump();
}
 
Example 10
Source File: WalkModFacade.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Initalizes a Walkmod service
 *  @param walkmodCfg
 *            Walkmod configuration file. If null, file named 'walkmod.xml' is searched at the
 *            root.
 * @param optionsArg
 *            Map of option. See {@link Options} and {@link OptionsBuilder} for available
 *            options and default values.
 * @param configurationProvider
 *            Configuration provider responsible for the resolution of plugins (used to use
 */
public WalkModFacade(/* @Nullable */ File walkmodCfg, Options optionsArg, ConfigurationProvider configurationProvider) {

    this.options = optionsArg;

    if (walkmodCfg != null) {
        this.cfg = walkmodCfg.getAbsoluteFile();
    } else {
        this.cfg = new File(options.getExecutionDirectory().getAbsolutePath(),
                DEFAULT_WALKMOD_FILE_NAME + "." + options.getConfigurationFormat());
    }

    if (configurationProvider != null)
        this.configurationProvider = configurationProvider;
}
 
Example 11
Source File: gaj.java    From Ngram-Graphs with Apache License 2.0 5 votes vote down vote up
public static double evalCharParams(int iCharMin, int iCharMax, int iCharDist) {
    // Check for results subdir
    File fRes = new File("results/");
    if (!fRes.exists()) {
        if (!fRes.mkdir())
            System.err.println("Cannot create results dir. Aborting...");
            return Double.NEGATIVE_INFINITY;
    }
    
    try {
        // Create output file
        File fTemp = File.createTempFile("sumeval",".table");

        // Eval summaries
        String []sParams = {"-charMin=" + iCharMin, "-charMax="+iCharMax, "-charDist="+iCharDist,
            "-do=char", "-o="+fTemp.getAbsoluteFile(), "-t=2", "-NOTs"}; // TODO: Change back to -s
        summaryEvaluator.main(sParams);
        // Calc overall results and correlation to responsiveness
        String[] sAssessorParams = {"-insectFile="+fTemp.getAbsoluteFile(), "-respFile=responsiveness.table", 
            "-dirPrefix=" + fRes.getPath() + "/", "-do=char", "-s"};
        resultAssessor.main(sAssessorParams);
        fTemp.delete();
        
    }
    catch (IOException ioe) {
        System.err.println("Cannot create results file. Aborting...");
        return Double.NEGATIVE_INFINITY;
        
    }
    
    System.err.println("Normalized value: " + normalizeResult(resultAssessor.LastExecRes));
    return normalizeResult(resultAssessor.LastExecRes);
}
 
Example 12
Source File: AquaFileChooserUI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds the directory to the model and sets it to be selected,
 * additionally clears out the previous selected directory and
 * the paths leading up to it, if any.
 */
void addItem(final File directory) {
    if (directory == null) { return; }
    if (fSelectedDirectory != null) {
        removeSelectedDirectory();
    }

    // create File instances of each directory leading up to the top
    File f = directory.getAbsoluteFile();
    final Vector<File> path = new Vector<File>(10);
    while (f.getParent() != null) {
        path.addElement(f);
        f = getFileChooser().getFileSystemView().createFileObject(f.getParent());
    };

    // Add root file (the desktop) to the model
    final File[] roots = getFileChooser().getFileSystemView().getRoots();
    for (final File element : roots) {
        path.addElement(element);
    }
    fPathCount = path.size();

    // insert all the path fDirectories leading up to the
    // selected directory in reverse order (current directory at top)
    for (int i = 0; i < path.size(); i++) {
        fDirectories.addElement(path.elementAt(i));
    }

    setSelectedItem(fDirectories.elementAt(0));

    // dump();
}
 
Example 13
Source File: GatewayServer.java    From knox with Apache License 2.0 4 votes vote down vote up
private static File calculateAbsoluteDeploymentsDir( GatewayConfig config ) {
  File deployDir = new File( config.getGatewayDeploymentDir() );
  deployDir = deployDir.getAbsoluteFile();
  return deployDir;
}
 
Example 14
Source File: GraalNativeMojo.java    From helidon-build-tools with Apache License 2.0 4 votes vote down vote up
/**
 * Find the {@code native-image} command file.
 *
 * @return File
 * @throws MojoExecutionException if unable to find the command file
 */
private File findNativeImageCmd() throws MojoExecutionException {

    if (graalVMHome == null
            || !graalVMHome.exists()
            || !graalVMHome.isDirectory()) {

        getLog().debug(
                "graalvm.home not set,looking in the PATH environment");

        String sysPath = System.getenv("PATH");
        if (sysPath == null || sysPath.isEmpty()) {
            throw new MojoExecutionException(
                    "PATH environment variable is unset or empty");
        }
        for (final String p : sysPath.split(File.pathSeparator)) {
            final File e = new File(p, NATIVE_IMAGE_CMD);
            if (e.isFile()) {
                return e.getAbsoluteFile();
            }
        }
        throw new MojoExecutionException(NATIVE_IMAGE_CMD
                + " not found in the PATH environment");
    }

    getLog().debug(
            "graalvm.home set, looking for bin/" + NATIVE_IMAGE_CMD);

    File binDir = new File(graalVMHome, "bin");
    if (!binDir.exists() || !binDir.isDirectory()) {
        throw new MojoExecutionException("Unable to find "
                + NATIVE_IMAGE_CMD + " command path, "
                + binDir.getAbsolutePath()
                + " is not a valid directory");
    }

    File cmd = new File(binDir, "native-image");
    if (!cmd.exists() || !cmd.isFile()) {
        throw new MojoExecutionException("Unable to find "
                + NATIVE_IMAGE_CMD + " command path, "
                + cmd.getAbsolutePath()
                + " is not a valid file");
    }
    getLog().debug("Found " + NATIVE_IMAGE_CMD + ": " + cmd);
    return cmd;
}
 
Example 15
Source File: SimpleIndexManager.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void returnIndexWriter(final EventIndexWriter writer, final boolean commit, final boolean isCloseable) {
    final File indexDirectory = writer.getDirectory();
    final File absoluteFile = indexDirectory.getAbsoluteFile();
    logger.trace("Returning Index Writer for {} to IndexManager", indexDirectory);

    boolean unused = false;
    IndexWriterCount count = null;
    boolean close = isCloseable;
    try {
        synchronized (writerCounts) {
            count = writerCounts.get(absoluteFile);
            if (count != null && count.isCloseableWhenUnused()) {
                close = true;
            }

            if (count == null) {
                logger.warn("Index Writer {} was returned to IndexManager for {}, but this writer is not known. "
                    + "This could potentially lead to a resource leak", writer, indexDirectory);
                writer.close();
            } else if (count.getCount() <= 1) {
                // we are finished with this writer.
                unused = true;
                if (close) {
                    logger.debug("Decrementing count for Index Writer for {} to {}; closing writer", indexDirectory, count.getCount() - 1);
                    writerCounts.remove(absoluteFile);
                } else {
                    logger.trace("Decrementing count for Index Writer for {} to {}", indexDirectory, count.getCount() - 1);

                    // If writer is not closeable, then we need to decrement its count.
                    writerCounts.put(absoluteFile, new IndexWriterCount(count.getWriter(), count.getAnalyzer(), count.getDirectory(),
                        count.getCount() - 1, close));
                }
            } else {
                // decrement the count.
                if (close) {
                    logger.debug("Decrementing count for Index Writer for {} to {} and marking as closeable when no longer in use", indexDirectory, count.getCount() - 1);
                } else {
                    logger.trace("Decrementing count for Index Writer for {} to {}", indexDirectory, count.getCount() - 1);
                }

                writerCounts.put(absoluteFile, new IndexWriterCount(count.getWriter(), count.getAnalyzer(),
                    count.getDirectory(), count.getCount() - 1, close));
            }

            if (writerCounts.size() > repoConfig.getStorageDirectories().size() * 2) {
                logger.debug("Index Writer returned; writer count map now has size {}; writer = {}, commit = {}, isCloseable = {}, writerCount = {}; full writerCounts Map = {}",
                    writerCounts.size(), writer, commit, isCloseable, count, writerCounts);
            }
        }

        // Committing and closing are very expensive, so we want to do those outside of the synchronized block.
        // So we use an 'unused' variable to tell us whether or not we should actually do so.
        if (unused) {
            try {
                if (commit) {
                    writer.commit();
                }
            } finally {
                if (close) {
                    logger.info("Index Writer for {} has been returned to Index Manager and is no longer in use. Closing Index Writer", indexDirectory);
                    close(count);
                }
            }
        }
    } catch (final Exception e) {
        logger.warn("Failed to close Index Writer {} due to {}", writer, e.toString(), e);
    }
}
 
Example 16
Source File: LibUtils.java    From Concurnas with MIT License 4 votes vote down vote up
/**
 * Load the library with the given name from a resource.
 * 
 * @param resourceSubdirectoryName
 *            The subdirectory where the resource is expected
 * @param libraryName
 *            The library name, e.g. "EXAMPLE-windows-x86"
 * @param tempSubdirectoryName
 *            The name for the subdirectory in the temp directory, where the
 *            temporary files for dependent libraries should be stored
 * @param dependentLibraryNames
 *            The names of libraries that the library to load depends on, and
 *            that may have to be loaded as resources and stored as temporary
 *            files as well
 * @throws Throwable
 *             If the library could not be loaded
 */
private static void loadLibraryResource(String resourceSubdirectoryName, String libraryName, String tempSubdirectoryName, String... dependentLibraryNames) throws Throwable {
	// First try to load all dependent libraries, recursively
	for (String dependentLibraryName : dependentLibraryNames) {
		logger.log(level, "Library " + libraryName + " depends on " + dependentLibraryName);

		String dependentResourceSubdirectoryName = resourceSubdirectoryName + "/" + osString() + "/" + archString();

		String dependentLibraryTempSubDirectoryName = libraryName + "_dependents" + File.separator + osString() + File.separator + archString() + File.separator;

		loadLibraryResource(dependentResourceSubdirectoryName, dependentLibraryName, dependentLibraryTempSubDirectoryName);
	}

	// Now, prepare loading the actual library
	String libraryFileName = createLibraryFileName(libraryName);
	File libraryTempFile;
	if (useUniqueLibraryNames()) {
		String uniqueLibraryFileName = createLibraryFileName(libraryName + "-" + UUID.randomUUID());
		libraryTempFile = createTempFile(tempSubdirectoryName, uniqueLibraryFileName);
	} else {
		libraryTempFile = createTempFile(tempSubdirectoryName, libraryFileName);
	}
	
	libraryTempFile = libraryTempFile.getAbsoluteFile();

	// If the temporary file for the library does not exist, create it
	if (!libraryTempFile.exists()) {
		String libraryResourceName = resourceSubdirectoryName + "/" + libraryFileName;
		logger.log(level, "Writing resource  " + libraryResourceName);
		logger.log(level, "to temporary file " + libraryTempFile);
		writeResourceToFile(libraryResourceName, libraryTempFile);
		if (trackCreatedTempFiles()) {
			LibTracker.track(libraryTempFile);
		}
	}

	// Finally, try to load the library from the temporary file
	logger.log(level, "Loading library " + libraryTempFile);
	System.load(libraryTempFile.toString());
	logger.log(level, "Loading library " + libraryTempFile + " DONE");
}
 
Example 17
Source File: DataUtils.java    From oodt with Apache License 2.0 4 votes vote down vote up
public static String createDatasetZipFile(ProductType type,
    String workingDirPath) throws IOException, CasProductException {
  String datasetZipFileName = type.getName() + ".zip";
  workingDirPath += workingDirPath.endsWith("/") ? "" : "/";
  String datasetZipFilePath = workingDirPath + datasetZipFileName;

  // try and remove it first
  if (!new File(datasetZipFilePath).delete()) {
    LOG.log(Level.WARNING, "Attempt to remove temp dataset zip file: ["
        + datasetZipFilePath + "] failed.");
  }

  // get a list of all the product zip files within the temp dir
  // assumption: the temp dir provided has a whole bunch of *.zip files
  // that are zips of the products (and their files and metadata)
  // belonging
  // to this dataset

  // NOTE: it is important that this step be done BEFORE creating the zip
  // output stream: else that will cause the generated datset zip to be
  // included as well!
  File[] productZipFiles = new File(workingDirPath).listFiles(ZIP_FILTER);
  if (productZipFiles == null || productZipFiles.length == 0)
  {
    throw new CasProductException("No product zip files to include in dataset: ["
        + type.getName() + "]");
  }

  // now get a reference to the zip file that we want to write
  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
      datasetZipFilePath));

  for (File productZipFile : productZipFiles) {
    String filename = productZipFile.getName();
    FileInputStream in = new FileInputStream(productZipFile
        .getAbsoluteFile());
    addZipEntryFromStream(in, out, filename);
    in.close();

    if (!productZipFile.delete()) {
      LOG.log(Level.WARNING, "Unable to remove tempoary product zip file: ["
                             + productZipFile.getAbsolutePath() + "]");
    } else {
      LOG.log(Level.INFO, "Deleting original product zip file: ["
                          + productZipFile.getAbsolutePath() + "]");
    }
  }

  // add met file
  addMetFileToProductZip(type.getTypeMetadata(), type.getName(), out);

  // Complete the ZIP file
  out.close();

  // return the zip file path
  return datasetZipFilePath;

}
 
Example 18
Source File: FileLocker.java    From datakernel with Apache License 2.0 4 votes vote down vote up
private FileLocker(File lockFile) {
	this.lockFile = lockFile.getAbsoluteFile();
}
 
Example 19
Source File: OracleClient.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/** Return a Map with information about tables and their indexes.
 * 
 * @return A Map containingMap where the key (String) is a the name of a table and the value
 *         is a List of index names (Strings) on that table.
 */
protected static Map<String, List<String>> getIndexMap() {
  final String INDEX_FILE_SUFFIX = "_index.inc";
  Map<String, List<String>> indexMap = new HashMap<String, List<String>>(); // key is table name, value is List of index names
  String dirPath = System.getProperty("JTESTS") + File.separator + "gfxdperf" + File.separator + "tpch";
  File dir = new File(dirPath);
  String[] dirContents = dir.list();
  for (String fileName: dirContents) {
    if (fileName.endsWith(INDEX_FILE_SUFFIX)) {
      FileLineReader flr;
      try {
        flr = new FileLineReader(dir.getAbsoluteFile() + File.separator + fileName);
      } catch (FileNotFoundException e) {
        String s = "Not able to find " + fileName;
        throw new PerfTestException(s);
      }
      String line = flr.readNextLine();
      while (line != null) {
        String[] tokens = line.split("[\\s]+");
        for (int i = 0; i < tokens.length; i++) {
          // looking for a line of the form "CREATE INDEX <indexName> ON <tableName>"
          if ((i+4 < tokens.length) && tokens[i].toLowerCase().endsWith("create") &&
              tokens[i+1].toLowerCase().equals("index") &&
              tokens[i+3].toLowerCase().equals("on")) {
            String indexName = tokens[i+2];
            String tableName = tokens[i+4];
            List<String> indexList = indexMap.get(tableName);
            if (indexList == null) {
              indexList = new ArrayList<String>();
            }
            indexList.add(indexName);
            indexMap.put(tableName, indexList);
            break;
          }
        }
        line = flr.readNextLine();
      }
    }
  }
  return indexMap;
}
 
Example 20
Source File: PitMojoIT.java    From pitest with Apache License 2.0 4 votes vote down vote up
private static String readResults(File testDir) throws IOException {
  File mutationReport = new File(testDir.getAbsoluteFile() + File.separator
      + "target" + File.separator + "pit-reports" + File.separator
      + "mutations.xml");
  return FileUtils.readFileToString(mutationReport);
}