java.io.File#isAbsolute ( )源码实例Demo

下面列出了java.io.File#isAbsolute ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: LibrariesSupport.java
/**
 * Properly converts possibly relative file path to URI.
 * @param path file path to convert; can be relative; cannot be null
 * @return uri
 * @since org.netbeans.modules.project.libraries/1 1.18
 */
public static URI convertFilePathToURI(final @NonNull String path) {
    Parameters.notNull("path", path);   //NOI18N
    try {
        File f = new File(path);
        if (f.isAbsolute()) {
            return BaseUtilities.toURI(f);
        } else {
            // create hierarchical relative URI (that is no schema)
            return new URI(null, null, path.replace('\\', '/'), null);
        }

    } catch (URISyntaxException ex) {
 IllegalArgumentException y = new IllegalArgumentException();
 y.initCause(ex);
 throw y;
    }
}
 
源代码2 项目: xds-ide   文件: SpellingPreferenceBlock.java
private void validateAbsoluteFilePath() {
    MyStatus ms = new MyStatus(IStatus.OK, XdsEditorsPlugin.PLUGIN_ID, null);
    String path = fDictionaryPath == null ? "" : fDictionaryPath.getText().trim(); //$NON-NLS-1$
    if (!path.isEmpty()) {
   	    IStringVariableManager variableManager= VariablesPlugin.getDefault().getStringVariableManager();
   	    try {
   	        path= variableManager.performStringSubstitution(path);
   	        if (path.length() > 0) {
   	            final File file= new File(path);
   	            if (!file.exists() || !file.isFile() || !file.isAbsolute() || !file.canRead()) {
                       ms = new MyStatus(IStatus.ERROR, XdsEditorsPlugin.PLUGIN_ID, Messages.SpellingPreferenceBlock_BadDictFile);
   	            } else if (!file.getParentFile().canWrite() || !file.canWrite()) {
   	                ms = new MyStatus(IStatus.ERROR, XdsEditorsPlugin.PLUGIN_ID, Messages.SpellingPreferenceBlock_RWAccessRequired);
   	            }
   	        }
   	    } catch (CoreException e) {
   	        ms = new MyStatus(IStatus.ERROR, XdsEditorsPlugin.PLUGIN_ID, e.getLocalizedMessage());
   	    }
    }
    
    if (ms.matches(IStatus.ERROR) || fFileStatus.matches(IStatus.ERROR)) {
        fFileStatus = ms;
        updateStatus();
    }
}
 
源代码3 项目: jmeter-bzm-plugins   文件: RandomCSVReader.java
public RandomCSVReader(String filename, String encoding,
                       String delim, boolean randomOrder,
                       boolean hasVariableNames, boolean firstLineIsHeader,
                       boolean isRewindOnEndOfList) {
    File f = new File(filename);
    this.file = (f.isAbsolute() || f.exists()) ? f : new File(FileServer.getFileServer().getBaseDir(), filename);
    this.encoding = encoding;
    this.delim = checkDelimiter(delim).charAt(0);
    this.isSkipFirstLine = !(!firstLineIsHeader && hasVariableNames);
    this.randomOrder = randomOrder;
    this.isRewindOnEndOfList = isRewindOnEndOfList;
    try {
        initOffsets();
        if (randomOrder) {
            initRandom();
        } else {
            initConsistentReader();
        }
        initHeader();
    } catch (IOException ex) {
        LOGGER.error("Cannot initialize RandomCSVReader, because of error: ", ex);
        throw new RuntimeException("Cannot initialize RandomCSVReader, because of error: " + ex.getMessage(), ex);
    }
}
 
源代码4 项目: eslint-plugin   文件: ESLintSettingsPage.java
private boolean validatePath(String path, boolean allowEmpty) {
    if (StringUtils.isEmpty(path)) {
        return allowEmpty;
    }
    File filePath = new File(path);
    if (filePath.isAbsolute()) {
        if (!filePath.exists() || !filePath.isFile()) {
            return false;
        }
    } else {
        if (project.isDefault()) {
            return false;
        }
        VirtualFile child = project.getBaseDir().findFileByRelativePath(path);
        if (child == null || !child.exists() || child.isDirectory()) {
            return false;
        }
    }
    return true;
}
 
private File computeDir(String dir) {
    File dirFile = new File(dir);
    if (dirFile.isAbsolute()) {
        return dirFile;
    } else {
        return new File(project.getBasedir(), buildDir).getAbsoluteFile();
    }
}
 
源代码6 项目: magarena   文件: Builder.java
public Cmd(File basedir) {
	_basedir = basedir;
	String path = System.getProperty("launch4j.bindir");
	if (path == null) {
		_bindir = new File(basedir, "bin");
	} else {
		File bindir = new File(path);
		_bindir = bindir.isAbsolute() ? bindir : new File(basedir, path);
	}
}
 
源代码7 项目: hottub   文件: SystemIDResolver.java
/**
 * 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();

}
 
源代码8 项目: jdk8u-jdk   文件: JFileChooser.java
/**
 * Sets the selected file. If the file's parent directory is
 * not the current directory, changes the current directory
 * to be the file's parent directory.
 *
 * @beaninfo
 *   preferred: true
 *       bound: true
 *
 * @see #getSelectedFile
 *
 * @param file the selected file
 */
public void setSelectedFile(File file) {
    File oldValue = selectedFile;
    selectedFile = file;
    if(selectedFile != null) {
        if (file.isAbsolute() && !getFileSystemView().isParent(getCurrentDirectory(), selectedFile)) {
            setCurrentDirectory(selectedFile.getParentFile());
        }
        if (!isMultiSelectionEnabled() || selectedFiles == null || selectedFiles.length == 1) {
            ensureFileIsVisible(selectedFile);
        }
    }
    firePropertyChange(SELECTED_FILE_CHANGED_PROPERTY, oldValue, selectedFile);
}
 
源代码9 项目: pushfish-android   文件: FileResourceConnector.java
private static File getFile(String absolutePath) {
    File f = new File(absolutePath);
    if (!f.isAbsolute()) {
        throw new IllegalArgumentException("Filename must be absolute: " + absolutePath);
    }
    return f;
}
 
源代码10 项目: jdk8u-dev-jdk   文件: JFileChooser.java
/**
 * Sets the selected file. If the file's parent directory is
 * not the current directory, changes the current directory
 * to be the file's parent directory.
 *
 * @beaninfo
 *   preferred: true
 *       bound: true
 *
 * @see #getSelectedFile
 *
 * @param file the selected file
 */
public void setSelectedFile(File file) {
    File oldValue = selectedFile;
    selectedFile = file;
    if(selectedFile != null) {
        if (file.isAbsolute() && !getFileSystemView().isParent(getCurrentDirectory(), selectedFile)) {
            setCurrentDirectory(selectedFile.getParentFile());
        }
        if (!isMultiSelectionEnabled() || selectedFiles == null || selectedFiles.length == 1) {
            ensureFileIsVisible(selectedFile);
        }
    }
    firePropertyChange(SELECTED_FILE_CHANGED_PROPERTY, oldValue, selectedFile);
}
 
/**
 * Tries to find a file in the given absolute path or relative to the HiveMQ home folder.
 *
 * @param fileLocation The absolute or relative path
 * @return a file
 */
private @NotNull File findAbsoluteAndRelative(final @NotNull String fileLocation) {
    final File file = new File(fileLocation);
    if (file.isAbsolute()) {
        return file;
    } else {
        return new File(systemInformation.getHiveMQHomeFolder(), fileLocation);
    }
}
 
源代码12 项目: jdk8u60   文件: HTMLWriter.java
/**
 * Write a hypertext link.
 * @param file the target for the link
 * @param body the body text for the link
 * @throws IOException if there is a problem closing the underlying stream
 */
public void writeLink(File file, String body) throws IOException {
    startTag(A);
    StringBuffer sb = new StringBuffer();
    String path = file.getPath().replace(File.separatorChar, '/');
    if (file.isAbsolute() && !path.startsWith("/"))
        sb.append('/');
    sb.append(path);
    writeAttr(HREF, sb.toString());
    write(body);
    endTag(A);
}
 
源代码13 项目: jdk8u-jdk   文件: FileSystemView.java
/**
 * 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;
}
 
源代码14 项目: opensim-gui   文件: FileUtils.java
/**
 * 
 * @param folder name of folder to search
 * @param baseName starting guess for unused filename located under folder
 * @return name of unused filename that can be created under folder in the form base_X 
 */
public static String getNextAvailableName(String folder, String baseName) {
    File baseFile = new File(baseName);
    if (baseFile.isAbsolute()){ // user specified a full path. Ignore passed in folder
        folder = baseFile.getParent();
    }
    else
        baseName = folder+baseName;
    // Here folder and baseName are consistent for a file and a parent directory
    File parentDir = new File(folder);
    // Handle extension
    String stripExtension = baseName.substring(0, baseName.lastIndexOf('.'));
    if (stripExtension.contains("_"))
        stripExtension = stripExtension.substring(0, baseName.lastIndexOf('_'));
    String extensionString = baseName.substring(baseName.lastIndexOf('.')); // includes .
    // Cycle thru and check if the file exists, return first available
    boolean found = false;
    int index=1;
    while(!found){
        String suffix = "_"+String.valueOf(index);
        File nextCandidate = new File(stripExtension+suffix+extensionString);
        if (!nextCandidate.exists()){
            return stripExtension+suffix+extensionString;
        }
        index++;
    }
    // unreached
    return null;
}
 
源代码15 项目: netbeans   文件: AbstractSvnTestCase.java
protected SVNUrl getFileUrl(File file) {
    if (file.isAbsolute()) {
        return getFileUrl(getPathRelativeToWC(file));
    } else {
        return getFileUrl(file.getPath());
    }
}
 
private static File getRootCauseDefinitionsFile(ThirdEyeDashboardConfiguration config) {
  if(config.getRootCause().getDefinitionsPath() == null)
    throw new IllegalArgumentException("definitionsPath must not be null");
  File rcaConfigFile = new File(config.getRootCause().getDefinitionsPath());
  if(!rcaConfigFile.isAbsolute())
    return new File(config.getRootDir() + File.separator + rcaConfigFile);
  return rcaConfigFile;
}
 
源代码17 项目: xipki   文件: CaConfs.java
private static String resolveFilePath(String filePath, String baseDir) {
  File file = new File(filePath);
  return file.isAbsolute() ? filePath : new File(baseDir, filePath).getPath();
}
 
源代码18 项目: datacollector   文件: TensorFlowProcessor.java
@Override
protected List<ConfigIssue> init() {
  List<ConfigIssue> issues = super.init();
  String[] modelTags = new String[conf.modelTags.size()];
  modelTags = conf.modelTags.toArray(modelTags);

  if (Strings.isNullOrEmpty(conf.modelPath)) {
    issues.add(getContext().createConfigIssue(
        Groups.TENSOR_FLOW.name(),
        TensorFlowConfigBean.MODEL_PATH_CONFIG,
        Errors.TENSOR_FLOW_01
    ));
    return issues;
  }

  try {
    File exportedModelDir = new File(conf.modelPath);
    if (!exportedModelDir.isAbsolute()) {
      exportedModelDir = new File(getContext().getResourcesDirectory(), conf.modelPath).getAbsoluteFile();
    }
    this.savedModel = SavedModelBundle.load(exportedModelDir.getAbsolutePath(), modelTags);
  } catch (TensorFlowException ex) {
    issues.add(getContext().createConfigIssue(
        Groups.TENSOR_FLOW.name(),
        TensorFlowConfigBean.MODEL_PATH_CONFIG,
        Errors.TENSOR_FLOW_02,
        ex
    ));
    return issues;
  }

  this.session = this.savedModel.session();
  this.conf.inputConfigs.forEach(inputConfig -> {
        Pair<String, Integer> key = Pair.of(inputConfig.operation, inputConfig.index);
        inputConfigMap.put(key, inputConfig);
      }
  );

  fieldPathEval = getContext().createELEval("conf.inputConfigs");
  fieldPathVars = getContext().createELVars();

  errorRecordHandler = new DefaultErrorRecordHandler(getContext());

  return issues;
}
 
源代码19 项目: datacollector   文件: MLeapProcessor.java
@Override
protected List<ConfigIssue> init() {
  List<ConfigIssue> configIssues = super.init();
  errorRecordHandler = new DefaultErrorRecordHandler(getContext());
  if (configIssues.isEmpty()) {
    try {
      File mLeapModel = new File(conf.modelPath);
      if (!mLeapModel.isAbsolute()) {
        mLeapModel = new File(getContext().getResourcesDirectory(), conf.modelPath).getAbsoluteFile();
      }
      MleapContext mleapContext = new ContextBuilder().createMleapContext();
      BundleBuilder bundleBuilder = new BundleBuilder();
      mLeapPipeline = bundleBuilder.load(mLeapModel, mleapContext).root();
    } catch (Exception ex) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.MODEL_PATH_CONFIG,
          Errors.MLEAP_00,
          ex
      ));
      return configIssues;
    }

    leapFrameBuilder = new LeapFrameBuilder();
    leapFrameSupport = new LeapFrameSupport();

    for (InputConfig inputConfig : conf.inputConfigs) {
      fieldNameMap.put(inputConfig.pmmlFieldName, inputConfig.fieldName);
    }

    // Validate Input fields
    StructType inputSchema = mLeapPipeline.inputSchema();
    List<StructField> structFieldList = leapFrameSupport.getFields(inputSchema);
    List<String> missingInputFieldNames = structFieldList.stream()
        .filter(structField -> !fieldNameMap.containsKey(structField.name()))
        .map(StructField::name)
        .collect(Collectors.toList());
    if (!missingInputFieldNames.isEmpty()) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.INPUT_CONFIGS_CONFIG,
          Errors.MLEAP_01,
          missingInputFieldNames
      ));
    }

    // Validate Output field names
    if (conf.outputFieldNames.size() == 0) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.OUTPUT_FIELD_NAMES_CONFIG,
          Errors.MLEAP_02
      ));
      return configIssues;
    }

    StructType outputSchema = mLeapPipeline.outputSchema();
    List<StructField> outputStructFieldList = leapFrameSupport.getFields(outputSchema);
    List<String> outputFieldNamesCopy = new ArrayList<>(conf.outputFieldNames);
    outputFieldNamesCopy.removeAll(
        outputStructFieldList.stream().map(StructField::name).collect(Collectors.toList())
    );
    if (outputFieldNamesCopy.size() > 0) {
      configIssues.add(getContext().createConfigIssue(
          Groups.MLEAP.name(),
          MLeapProcessorConfigBean.OUTPUT_FIELD_NAMES_CONFIG,
          Errors.MLEAP_03,
          outputFieldNamesCopy
      ));
    }

  }
  return configIssues;
}
 
private File[] processCommandLine(String[] argsArray) {

		ArrayList args = new ArrayList();
		for (int i = 0, max = argsArray.length; i < max; i++) {
			args.add(argsArray[i]);
		}
		int index = 0;
		final int argCount = argsArray.length;

		final int DEFAULT_MODE = 0;
		final int CONFIG_MODE = 1;

		int mode = DEFAULT_MODE;
		final int INITIAL_SIZE = 1;
		int fileCounter = 0;

		File[] filesToFormat = new File[INITIAL_SIZE];

		loop: while (index < argCount) {
			String currentArg = argsArray[index++];

			switch(mode) {
				case DEFAULT_MODE :
					if (PDE_LAUNCH.equals(currentArg)) {
						continue loop;
					}
					if (ARG_HELP.equals(currentArg)) {
						displayHelp();
						return null;
					}
					if (ARG_VERBOSE.equals(currentArg)) {
						this.verbose = true;
						continue loop;
					}
					if (ARG_QUIET.equals(currentArg)) {
						this.quiet = true;
						continue loop;
					}
					if (ARG_CONFIG.equals(currentArg)) {
						mode = CONFIG_MODE;
						continue loop;
					}
					// the current arg should be a file or a directory name
					File file = new File(currentArg);
					if (file.exists()) {
						if (filesToFormat.length == fileCounter) {
							System.arraycopy(filesToFormat, 0, (filesToFormat = new File[fileCounter * 2]), 0, fileCounter);
						}
						filesToFormat[fileCounter++] = file;
					} else {
						String canonicalPath;
						try {
							canonicalPath = file.getCanonicalPath();
						} catch(IOException e2) {
							canonicalPath = file.getAbsolutePath();
						}
						String errorMsg = file.isAbsolute()?
										  Messages.bind(Messages.CommandLineErrorFile, canonicalPath):
										  Messages.bind(Messages.CommandLineErrorFileTryFullPath, canonicalPath);
						displayHelp(errorMsg);
						return null;
					}
					break;
				case CONFIG_MODE :
					this.configName = currentArg;
					this.options = readConfig(currentArg);
					if (this.options == null) {
						displayHelp(Messages.bind(Messages.CommandLineErrorConfig, currentArg));
						return null;
					}
					mode = DEFAULT_MODE;
					continue loop;
			}
		}

		if (mode == CONFIG_MODE || this.options == null) {
			displayHelp(Messages.bind(Messages.CommandLineErrorNoConfigFile));
			return null;
		}
		if (this.quiet && this.verbose) {
			displayHelp(
				Messages.bind(
					Messages.CommandLineErrorQuietVerbose,
					new String[] { ARG_QUIET, ARG_VERBOSE }
				));
			return null;
		}
		if (fileCounter == 0) {
			displayHelp(Messages.bind(Messages.CommandLineErrorFileDir));
			return null;
		}
		if (filesToFormat.length != fileCounter) {
			System.arraycopy(filesToFormat, 0, (filesToFormat = new File[fileCounter]), 0, fileCounter);
		}
		return filesToFormat;
	}