Java Code Examples for java.io.File.isAbsolute()

The following are Jave code examples for showing how to use isAbsolute() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openrouteservice   File: LoggingUtility.java   View Source Code Vote up 6 votes
public static void init(String logsPath) throws Exception
{
	if (LoggingSettings.getEnabled())
	{
		String location = LoggingSettings.getLevelFile();

		if (location != null)
		{
			File configFile = Paths.get(logsPath, location).toFile();
			if (configFile.exists())
			{
				File outputPath  = Paths.get(LoggingSettings.getLocation()).toFile();
				
				if (!outputPath.isAbsolute())
				   outputPath = Paths.get(logsPath, LoggingSettings.getLocation()).toFile();
				
				initInternal(configFile, outputPath.toString(), LoggingSettings.getStdOut());
			}
			else
				throw new Exception("Logging config file does not exist.");
		}
	}
}
 
Example 2
Project: incubator-netbeans   File: FileEditor.java   View Source Code Vote up 6 votes
/** Should create a string insertable to the newly generated source code.
 * @return initialization string
 */
public String getJavaInitializationString() {
    File value = (File) getValue ();
    if (value == null) {
        return "null"; // NOI18N
    } else {
        // [PENDING] not a full escape of filenames, but enough to at least
        // handle normal Windows backslashes
        if (baseDirectory != null && !value.isAbsolute()) {
            return "new java.io.File(" // NOI18N
                + stringify(baseDirectory.getPath())
                + ", " // NOI18N
                + stringify(value.getPath())
                + ")"; // NOI18N
        } else {
            return "new java.io.File(" // NOI18N
                + stringify(value.getAbsolutePath())
                + ")"; // NOI18N
        }
    }
}
 
Example 3
Project: OpenJSharp   File: SystemIDResolver.java   View Source Code Vote up 5 votes
/**
 * Return true if the local path is an absolute path.
 *
 * @param systemId The path string
 * @return true if the path is absolute
 */
public static boolean isAbsolutePath(String systemId)
{
  if(systemId == null)
      return false;
  final File file = new File(systemId);
  return file.isAbsolute();

}
 
Example 4
Project: incubator-netbeans   File: NetbinoxFactory.java   View Source Code Vote up 5 votes
private static String findInstallArea() {
    String ia = System.getProperty("netbeans.home"); // NOI18N
    LOG.log(Level.FINE, "Home is {0}", ia);
    String rest = System.getProperty("netbeans.dirs"); // NOI18N
    if (rest != null) {
        for (String c : rest.split(File.pathSeparator)) {
            File cf = new File(c);
            if (!cf.isAbsolute() || !cf.exists()) {
                LOG.log(Level.FINE, "Skipping non-existent {0}", c);
                continue;
            }
            int prefix = findCommonPrefix(ia, c);
            if (prefix == ia.length()) {
                LOG.log(Level.FINE, "No change to prefix by {0}", c);
                continue;
            }
            if (prefix <= 3) {
                LOG.log(Level.WARNING, "Cannot compute install area. No common prefix between {0} and {1}", new Object[]{ia, c});
            } else {
                LOG.log(Level.FINE, "Prefix shortened by {0} to {1} chars", new Object[]{c, prefix});
                ia = ia.substring(0, prefix);
                LOG.log(Level.FINE, "New prefix {0}", ia);
            }
        }
    } else {
        LOG.fine("No dirs");
    }
    return ia;
}
 
Example 5
Project: instalint   File: DefaultFilePredicates.java   View Source Code Vote up 5 votes
@Override
public FilePredicate hasPath(String s) {
  File file = new File(s);
  if (file.isAbsolute()) {
    return hasAbsolutePath(s);
  }
  return hasRelativePath(s);
}
 
Example 6
Project: jdk8u-jdk   File: AquaFileChooserUI.java   View Source Code Vote up 5 votes
File makeFile(final JFileChooser fc, final String filename) {
    File selectedFile = null;
    // whitespace is legal on Macs, even on beginning and end of filename
    if (filename != null && !filename.equals("")) {
        final FileSystemView fs = fc.getFileSystemView();
        selectedFile = fs.createFileObject(filename);
        if (!selectedFile.isAbsolute()) {
            selectedFile = fs.createFileObject(fc.getCurrentDirectory(), filename);
        }
    }
    return selectedFile;
}
 
Example 7
Project: OpenJSharp   File: SystemIDResolver.java   View Source Code Vote up 5 votes
/**
 * Return true if the local path is an absolute path.
 *
 * @param systemId The path string
 * @return true if the path is absolute
 */
public static boolean isAbsolutePath(String systemId)
{
  if(systemId == null)
      return false;
  final File file = new File(systemId);
  return file.isAbsolute();

}
 
Example 8
Project: alfresco-repository   File: OpenOfficeVariant.java   View Source Code Vote up 5 votes
public File findExecutable(String executableName)
{
    File file = new File(executableName);
    if (file.isAbsolute())
    {
        file = canExecute(file);
    }
    else
    {
        file = findExecutableOnPath(executableName);
    }
    return file;
}
 
Example 9
Project: incubator-netbeans   File: SourceMapsTranslator.java   View Source Code Vote up 5 votes
static FileObject getSourceFile(String sourcePath, FileObject parentFolder) {
    File sourceFile = new File(sourcePath);
    FileObject fo;
    if (sourceFile.isAbsolute()) {
        fo = FileUtil.toFileObject(FileUtil.normalizeFile(sourceFile));
    } else {
        fo = parentFolder.getFileObject(sourcePath);
    }
    return fo;
}
 
Example 10
Project: BiglyBT   File: DownloadManagerDefaultPaths.java   View Source Code Vote up 5 votes
public static File normaliseRelativePath(File path) {
	if (path.isAbsolute()) {return null;}

	File parent = path.getParentFile();
	String child_name = normaliseRelativePathPart(path.getName());
	if (child_name == null) {
		return null;
	}

	//  Simple one-level path.
	if (parent == null) {
		return new File(child_name);
	}

	ArrayList parts = new ArrayList();
	parts.add(child_name);

	String filepart = null;
	while (parent != null) {
		filepart = normaliseRelativePathPart(parent.getName());
		if (filepart == null) {return null;}
		else if (filepart.length()==0) {/* continue */}
		else {parts.add(0, filepart);}
		parent = parent.getParentFile();
	}

	StringBuilder sb = new StringBuilder((String)parts.get(0));
	for (int i=1; i<parts.size(); i++) {
		sb.append(File.separatorChar);
		sb.append(parts.get(i));
	}

	return new File(sb.toString());
}
 
Example 11
Project: instalint   File: DefaultFilePredicates.java   View Source Code Vote up 5 votes
@Override
public FilePredicate is(File ioFile) {
  if (ioFile.isAbsolute()) {
    return hasAbsolutePath(ioFile.getAbsolutePath());
  }
  return hasRelativePath(ioFile.getPath());
}
 
Example 12
Project: incubator-netbeans   File: ExternalExecutableValidator.java   View Source Code Vote up 5 votes
@NbBundle.Messages({
    "# {0} - source",
    "ExternalExecutableValidator.validateFile.missing={0} must be selected.",
    "# {0} - source",
    "ExternalExecutableValidator.validateFile.notAbsolute={0} must be an absolute path.",
    "# {0} - source",
    "ExternalExecutableValidator.validateFile.notFile={0} must be a valid file.",
    "# {0} - source",
    "ExternalExecutableValidator.validateFile.notReadable={0} is not readable.",
    "# {0} - source",
    "ExternalExecutableValidator.validateFile.notWritable={0} is not writable."
})
@CheckForNull
private static String validateFile(String source, String filePath, boolean writable) {
    if (filePath == null
            || filePath.trim().isEmpty()) {
        return Bundle.ExternalExecutableValidator_validateFile_missing(source);
    }

    File file = new File(filePath);
    if (!file.isAbsolute()) {
        return Bundle.ExternalExecutableValidator_validateFile_notAbsolute(source);
    } else if (!file.isFile()) {
        return Bundle.ExternalExecutableValidator_validateFile_notFile(source);
    } else if (!file.canRead()) {
        return Bundle.ExternalExecutableValidator_validateFile_notReadable(source);
    } else if (writable && !file.canWrite()) {
        return Bundle.ExternalExecutableValidator_validateFile_notWritable(source);
    }
    return null;
}
 
Example 13
Project: nb-clojure   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * Validate a file path and return {@code null} if it is valid, otherwise an error.
 * <p>
 * A valid file means that the <tt>filePath</tt> represents a valid, readable file
 * with absolute file path.
 * @param source source used in error message (e.g. "Script", "Config file")
 * @param filePath a file path to validate
 * @param writable {@code true} if the file must be writable, {@code false} otherwise
 * @return {@code null} if it is valid, otherwise an error
 */
@NbBundle.Messages({
    "# {0} - source",
    "FileUtils.validateFile.missing={0} must be selected.",
    "# {0} - source",
    "FileUtils.validateFile.notAbsolute={0} must be an absolute path.",
    "# {0} - source",
    "FileUtils.validateFile.notFile={0} must be a valid file.",
    "# {0} - source",
    "FileUtils.validateFile.notReadable={0} is not readable.",
    "# {0} - source",
    "FileUtils.validateFile.notWritable={0} is not writable."
})
@CheckForNull
public static String validateFile(String source, String filePath, boolean writable) {
    if (!StringUtils.hasText(filePath)) {
        return Bundle.FileUtils_validateFile_missing(source);
    }

    File file = new File(filePath);
    if (!file.isAbsolute()) {
        return Bundle.FileUtils_validateFile_notAbsolute(source);
    } else if (!file.isFile()) {
        return Bundle.FileUtils_validateFile_notFile(source);
    } else if (!file.canRead()) {
        return Bundle.FileUtils_validateFile_notReadable(source);
    } else if (writable && !file.canWrite()) {
        return Bundle.FileUtils_validateFile_notWritable(source);
    }
    return null;
}
 
Example 14
Project: OpenJSharp   File: FileSystemView.java   View Source Code Vote up 5 votes
/**
 * Determines if the given file is a root in the navigable tree(s).
 * Examples: Windows 98 has one root, the Desktop folder. DOS has one root
 * per drive letter, <code>C:\</code>, <code>D:\</code>, etc. Unix has one root,
 * the <code>"/"</code> directory.
 *
 * The default implementation gets information from the <code>ShellFolder</code> class.
 *
 * @param f a <code>File</code> object representing a directory
 * @return <code>true</code> if <code>f</code> is a root in the navigable tree.
 * @see #isFileSystemRoot
 */
public boolean isRoot(File f) {
    if (f == null || !f.isAbsolute()) {
        return false;
    }

    File[] roots = getRoots();
    for (File root : roots) {
        if (root.equals(f)) {
            return true;
        }
    }
    return false;
}
 
Example 15
Project: monarch   File: FilePathStringConverter.java   View Source Code Vote up 4 votes
@Override
public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType,
    String existingData, String optionContext, MethodTarget target) {
  // prefix is needed while comparing Completion Candidates as potential matches
  String prefixToUse = "";
  boolean prependAbsolute = true;
  File parentDir = null; // directory to be searched for file(s)

  if (existingData != null) {
    // System.out.println("FilePathConverter.getAllPossibleValues() : optionContext ::
    // "+optionContext+", existingData : "+existingData);
    String[] completionValues = new String[0];

    if (ConverterHint.FILE_PATHSTRING.equals(optionContext)) {
      // if existingData is empty, start from root
      if (existingData != null && existingData.trim().isEmpty()) {
        File[] listRoots = File.listRoots();
        completionValues = new String[listRoots.length];
        for (int i = 0; i < listRoots.length; i++) {
          completionValues[i] = listRoots[i].getPath();
        }
        prefixToUse = File.separator;
      } else {
        // Create a file from existing data
        File file = new File(existingData);
        if (file.isDirectory()) {
          // For a directory, list files/sub-dirsin the directory
          parentDir = file;
          completionValues = parentDir.list();
        } else if (!file.exists()) {
          parentDir = file.getParentFile();
          if (parentDir == null) {
            try {
              parentDir = file.getCanonicalFile().getParentFile();
            } catch (IOException e) {
              parentDir = null;
            }
          }
          if (parentDir != null) {
            completionValues = parentDir.list(new FileNameFilterImpl(parentDir, file.getName()));
          }
        }
        // whether the file path is absolute
        prependAbsolute = file.isAbsolute();
      }
    }

    if (completionValues.length > 0) {
      // use directory path as prefix for completion of names of the contained files
      if (parentDir != null) {
        if (existingData.startsWith(".")) { // handle . & ..
          prefixToUse = parentDir.getPath();
        } else if (prependAbsolute) {
          prefixToUse = parentDir.getAbsolutePath();
        }
      }
      // add File.separator in the end
      if (!prefixToUse.endsWith(File.separator)
          && (prependAbsolute || existingData.startsWith("."))) {
        prefixToUse += File.separator;
      }
      for (int i = 0; i < completionValues.length; i++) {
        completions.add(new Completion(prefixToUse + completionValues[i]));
      }
    }
  }

  return !completions.isEmpty();
}
 
Example 16
Project: incubator-netbeans   File: JavaActions.java   View Source Code Vote up 4 votes
/**
 * Make sure that the custom build script imports the original build script
 * and is using the same base dir.
 * Used for generated targets which essentially copy Ant targets from build.xml.
 * Use with {@link #GENERAL_SCRIPT_PATH}.
 * Idempotent, takes effect only once.
 * @param antProject XML of an Ant project (document element)
 * @oaram origScriptPath Ant name of original build script's path
 */
void ensureImports(Element antProject, String origScriptPath) throws IOException, SAXException {
    if (antProject.getAttribute("basedir").length() > 0) {
        // Do not do it twice to the same script.
        return;
    }
    String origScriptPathEval = evaluator.evaluate(origScriptPath);
    if (origScriptPathEval == null) {
        // Can't do anything, forget it.
        return;
    }
    String origScriptURI = Utilities.toURI(helper.resolveFile(origScriptPathEval)).toString();
    Document origScriptDocument = XMLUtil.parse(new InputSource(origScriptURI), false, true, null, null);
    String origBasedir = origScriptDocument.getDocumentElement().getAttribute("basedir"); // NOI18N
    if (origBasedir.length() == 0) {
        origBasedir = "."; // NOI18N
    }
    String basedir, importPath;
    File origScript = new File(origScriptPathEval);
    if (origScript.isAbsolute()) {
        // Use full path.
        importPath = origScriptPathEval;
        if (new File(origBasedir).isAbsolute()) {
            basedir = origBasedir;
        } else {
            basedir = PropertyUtils.resolveFile(origScript.getParentFile(), origBasedir).getAbsolutePath();
        }
    } else {
        // Import relative to that path.
        // Note that <import>'s path is always relative to the location of the importing script, regardless of the basedir.
        String prefix = /* ".." times count('/', FILE_SCRIPT_PATH) */"../"; // NOI18N
        importPath = prefix + origScriptPathEval;
        if (new File(origBasedir).isAbsolute()) {
            basedir = origBasedir;
        } else {
            int slash = origScriptPathEval.replace(File.separatorChar, '/').lastIndexOf('/');
            if (slash == -1) {
                basedir = prefix + origBasedir;
            } else {
                basedir = prefix + origScriptPathEval.substring(0, slash + 1) + origBasedir;
            }
            // Trim:
            basedir = basedir.replaceAll("/\\.$", ""); // NOI18N
        }
    }
    antProject.setAttribute("basedir", basedir); // NOI18N
    Element importEl = antProject.getOwnerDocument().createElement("import"); // NOI18N
    importEl.setAttribute("file", importPath); // NOI18N
    antProject.appendChild(importEl);
}
 
Example 17
Project: classchecks   File: TrainFaces.java   View Source Code Vote up 4 votes
/**
 * 以CSV文件提供的人脸图片训练人脸模型并保存模型文件(以XML的形式)
 * @param CSVFilePath csv文件存储的绝对路径
 * @param trainModellSavePath 训练的模型文件的保存路径
 */
public static boolean trainAndSaveModel(String CSVFilePath, String trainModelSavePath, String facerecAlgorithm) {
	
	if(!new File(CSVFilePath).isFile()) {
		return false;
	}
	// 判断要保存的人脸模型文件是不是一个绝对路径名
	File modelFile = new File(trainModelSavePath);
	if(!modelFile.isAbsolute()) {
		System.out.println("TrainFaces->trainAndSaveModel->trainModelSavePath不是一个绝对路径名");
		return false;
	}
	// 如果trainModelSavePath的上一级文件夹不存在则创建
	if(!modelFile.getParentFile().exists()) {
		modelFile.getParentFile().mkdirs();
	}
	
	List<Mat> matLists = new ArrayList<Mat>(); // 待训练的人脸图片集合
	List<Integer> lableLists = new ArrayList<Integer>(); // 人脸图片对应的标签
	CSVFileUtils.CSVRead(CSVFilePath, matLists, lableLists);
	
	// opencv 在训练人脸模型时需要确保人脸与标签一一对应
	if(matLists.size() == lableLists.size()) {
		Mat labels = new Mat(lableLists.size(), 1, CvType.CV_32SC1, new Scalar(0));
		for(int i = 0; i < lableLists.size(); i ++) {
			labels.put(i, 0, new int[]{lableLists.get(i)});
		}
		BasicFaceRecognizer faceRecognizer = null;
		if("FaceRecognizer.Eigenfaces".equals(facerecAlgorithm)) {
			faceRecognizer = Face.createEigenFaceRecognizer();
		} else if("FaceRecognizer.Fisherfaces".equals(facerecAlgorithm)) {
			faceRecognizer = Face.createFisherFaceRecognizer();
		}
		
		faceRecognizer.train(matLists, labels);
		faceRecognizer.save(trainModelSavePath);
		return true;
	}
	
	return false;
}
 
Example 18
Project: incubator-netbeans   File: FileEditor.java   View Source Code Vote up 4 votes
/**
 * This method is called by the IDE to pass
 * the environment to the property editor.
 * @param env Environment passed by the ide.
 */
public void attachEnv(PropertyEnv env) {
    this.env = env;

    // clearing to defaults
    directories = true;
    files = true;
    fileFilter = null;
    fileHiding = false;

    Object dirs = env.getFeatureDescriptor().getValue(PROPERTY_SHOW_DIRECTORIES);
    if (dirs instanceof Boolean) {
        directories = ((Boolean)dirs).booleanValue();
    } // XXX else if != null, warn
    Object fil = env.getFeatureDescriptor().getValue(PROPERTY_SHOW_FILES);
    if (fil instanceof Boolean) {
        files = ((Boolean)fil).booleanValue();
    } // XXX else if != null, warn
    Object filter = env.getFeatureDescriptor().getValue(PROPERTY_FILTER);
    if (filter instanceof FilenameFilter) {
        fileFilter = new DelegatingFilenameFilter((FilenameFilter)filter);
    } else if (filter instanceof javax.swing.filechooser.FileFilter) {
        fileFilter = (javax.swing.filechooser.FileFilter)filter;
    } else if (filter instanceof java.io.FileFilter) {
        fileFilter = new DelegatingFileFilter((java.io.FileFilter)filter);
    } // XXX else if != null, warn

    Object curDir = env.getFeatureDescriptor().getValue(PROPERTY_CURRENT_DIR);
    if (curDir instanceof File) {
        currentDirectory = (File)curDir;
        if(! currentDirectory.isDirectory()) {
            Logger.getAnonymousLogger().warning("java.io.File will not accept currentDir=" + currentDirectory); // NOI18N
            currentDirectory = null;
        }
    } // XXX else if != null, warn

    Object baseDir = env.getFeatureDescriptor().getValue(PROPERTY_BASE_DIR);
    if(baseDir instanceof File) {
        baseDirectory = (File)baseDir;
        // As baseDir accept only directories in their absolute form.
        if(!baseDirectory.isDirectory() || !baseDirectory.isAbsolute()) {
            Logger.getAnonymousLogger().warning("java.io.File will not accept baseDir=" + baseDirectory); // NOI18N
            baseDirectory = null;
        }
    } // XXX else if != null, warn
    if (files) {
        mode = directories ? JFileChooser.FILES_AND_DIRECTORIES : 
            JFileChooser.FILES_ONLY;
    } else {
        mode = directories ? JFileChooser.DIRECTORIES_ONLY :
            JFileChooser.FILES_AND_DIRECTORIES; // both false, what now? XXX warn
    }
    
    Object fileHide = env.getFeatureDescriptor().getValue(PROPERTY_FILE_HIDING);
    if (fileHide instanceof Boolean) {
        fileHiding = ((Boolean)fileHide).booleanValue();
    }
    
    if (env.getFeatureDescriptor() instanceof Node.Property){
        Node.Property prop = (Node.Property)env.getFeatureDescriptor();
        editable = prop.canWrite();
    }
}
 
Example 19
Project: openjdk-jdk10   File: SecurityManager.java   View Source Code Vote up 3 votes
/**
 * Throws a <code>SecurityException</code> if the
 * calling thread is not allowed to create a subprocess.
 * <p>
 * This method is invoked for the current security manager by the
 * <code>exec</code> methods of class <code>Runtime</code>.
 * <p>
 * This method calls <code>checkPermission</code> with the
 * <code>FilePermission(cmd,"execute")</code> permission
 * if cmd is an absolute path, otherwise it calls
 * <code>checkPermission</code> with
 * <code>FilePermission("&lt;&lt;ALL FILES&gt;&gt;","execute")</code>.
 * <p>
 * If you override this method, then you should make a call to
 * <code>super.checkExec</code>
 * at the point the overridden method would normally throw an
 * exception.
 *
 * @param      cmd   the specified system command.
 * @exception  SecurityException if the calling thread does not have
 *             permission to create a subprocess.
 * @exception  NullPointerException if the <code>cmd</code> argument is
 *             <code>null</code>.
 * @see     java.lang.Runtime#exec(java.lang.String)
 * @see     java.lang.Runtime#exec(java.lang.String, java.lang.String[])
 * @see     java.lang.Runtime#exec(java.lang.String[])
 * @see     java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
 * @see     #checkPermission(java.security.Permission) checkPermission
 */
public void checkExec(String cmd) {
    File f = new File(cmd);
    if (f.isAbsolute()) {
        checkPermission(new FilePermission(cmd,
            SecurityConstants.FILE_EXECUTE_ACTION));
    } else {
        checkPermission(new FilePermission("<<ALL FILES>>",
            SecurityConstants.FILE_EXECUTE_ACTION));
    }
}
 
Example 20
Project: OpenJSharp   File: JavacFileManager.java   View Source Code Vote up 3 votes
/**
 * Converts a relative file name to a relative URI.  This is
 * different from File.toURI as this method does not canonicalize
 * the file before creating the URI.  Furthermore, no schema is
 * used.
 * @param file a relative file name
 * @return a relative URI
 * @throws IllegalArgumentException if the file name is not
 * relative according to the definition given in {@link
 * javax.tools.JavaFileManager#getFileForInput}
 */
public static String getRelativeName(File file) {
    if (!file.isAbsolute()) {
        String result = file.getPath().replace(File.separatorChar, '/');
        if (isRelativeUri(result))
            return result;
    }
    throw new IllegalArgumentException("Invalid relative path: " + file);
}