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

The following examples show how to use java.io.File#getParentFile() . 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: ScpOperationBuilder.java    From teamcity-deployer-plugin with Apache License 2.0 6 votes vote down vote up
private static ScpOperation doCreatePathOperation(@NotNull final String remotePath,
                                                  @Nullable final ScpOperation chainTailOperation) {
  final String normalisedPath = remotePath.replaceAll("\\\\", "/");
  File remoteDir = new File(normalisedPath);
  DirScpOperation childOperation = new DirScpOperation(remoteDir.getName());
  if (null != chainTailOperation) {
    childOperation.add(chainTailOperation);
  }
  remoteDir = remoteDir.getParentFile();
  String name = remoteDir != null ? remoteDir.getName() : "";
  while (remoteDir != null && !StringUtil.isEmpty(name)) {

    final DirScpOperation directoryOperation = new DirScpOperation(name);
    directoryOperation.add(childOperation);

    childOperation = directoryOperation;
    remoteDir = remoteDir.getParentFile();
    if (remoteDir != null) {
      name = remoteDir.getName();
    }
  }
  return childOperation;
}
 
Example 2
Source File: Flat.java    From pegasus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the addOn part that is retrieved from the File Factory. It creates a new file in the
 * factory for the LFN and returns it.
 *
 * @param job
 * @param lfn the LFN to be used
 * @param site the site at which the LFN resides
 * @return
 */
public File mapToRelativeDirectory(Job job, SiteCatalogEntry site, String lfn) {
    // In the Flat hierarchy, all files are placed on the same directory.
    // we just let the factory create a new addOn space in the base directory
    // for the lfn
    File addOn = null;
    try {
        // the factory will give us the relative
        // add on part
        // PM-1131 figure out the last addon directory taking into
        // account deep lfns
        // addOn = mFactory.createFile( lfn ).getParentFile();
        File relative = mFactory.createFile(lfn);
        File deepLFN = new File(lfn);
        addOn = relative;
        while (deepLFN != null) {
            deepLFN = deepLFN.getParentFile();
            addOn = addOn.getParentFile();
        }
    } catch (IOException e) {
        throw new MapperException("IOException ", e);
    }

    return addOn;
}
 
Example 3
Source File: WindowsFileChooserUI.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void calculateDepths() {
    depths = new int[directories.size()];
    for (int i = 0; i < depths.length; i++) {
        File dir = directories.get(i);
        File parent = dir.getParentFile();
        depths[i] = 0;
        if (parent != null) {
            for (int j = i-1; j >= 0; j--) {
                if (parent.equals(directories.get(j))) {
                    depths[i] = depths[j] + 1;
                    break;
                }
            }
        }
    }
}
 
Example 4
Source File: ArcDigitalAssetStoreSOAPService.java    From webcurator with Apache License 2.0 6 votes vote down vote up
/** @see DigitalAssetStoreSOAP#save(String, String[], DataHandler[]). */
public void save(String targetInstanceName, String[] filenames, DataHandler[] files) throws DigitalAssetStoreException {
	File[] realFiles = new File[files.length];
	// Rename the files to have the right names.
	for(int i=0; i<files.length;i++) {
		File oldFile = new File(files[i].getName());
		realFiles[i] = new File(oldFile.getParentFile(), filenames[i]);
		
           if (log.isDebugEnabled()) {
               log.debug("SOAPService renaming " + oldFile.getAbsolutePath() + " to " + realFiles[i].getAbsolutePath());
           }
		oldFile.renameTo(realFiles[i]);
	}
	
	service.save(targetInstanceName, realFiles);
}
 
Example 5
Source File: FileSystemView.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * On Windows, a file can appear in multiple folders, other than its
 * parent directory in the filesystem. Folder could for example be the
 * "Desktop" folder which is not the same as file.getParentFile().
 *
 * @param folder a <code>File</code> object representing a directory or special folder
 * @param file a <code>File</code> object
 * @return <code>true</code> if <code>folder</code> is a directory or special folder and contains <code>file</code>.
 * @since 1.4
 */
public boolean isParent(File folder, File file) {
    if (folder == null || file == null) {
        return false;
    } else if (folder instanceof ShellFolder) {
            File parent = file.getParentFile();
            if (parent != null && parent.equals(folder)) {
                return true;
            }
        File[] children = getFiles(folder, false);
        for (File child : children) {
            if (file.equals(child)) {
                return true;
            }
        }
        return false;
    } else {
        return folder.equals(file.getParentFile());
    }
}
 
Example 6
Source File: GatewayMultiFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
public static void setupGateway() throws Exception {
  File targetDir = new File( System.getProperty( "user.dir" ), "target" );
  File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
  gatewayDir.mkdirs();

  config = new GatewayTestConfig();
  config.setGatewayHomeDir( gatewayDir.getAbsolutePath() );

  URL svcsFileUrl = TestUtils.getResourceUrl( DAT, "services/readme.txt" );
  File svcsFile = new File( svcsFileUrl.getFile() );
  File svcsDir = svcsFile.getParentFile();
  config.setGatewayServicesDir( svcsDir.getAbsolutePath() );

  URL appsFileUrl = TestUtils.getResourceUrl( DAT, "applications/readme.txt" );
  File appsFile = new File( appsFileUrl.getFile() );
  File appsDir = appsFile.getParentFile();
  config.setGatewayApplicationsDir( appsDir.getAbsolutePath() );

  File topoDir = new File( config.getGatewayTopologyDir() );
  topoDir.mkdirs();

  File descDir = new File( config.getGatewayDescriptorsDir() );
  descDir.mkdirs();

  File provConfDir = new File( config.getGatewayProvidersConfigDir() );
  provConfDir.mkdirs();

  File deployDir = new File( config.getGatewayDeploymentDir() );
  deployDir.mkdirs();

  startGatewayServer();
}
 
Example 7
Source File: FsDatasetUtil.java    From big-c with Apache License 2.0 5 votes vote down vote up
static File getOrigFile(File unlinkTmpFile) {
  final String name = unlinkTmpFile.getName();
  if (!name.endsWith(DatanodeUtil.UNLINK_BLOCK_SUFFIX)) {
    throw new IllegalArgumentException("unlinkTmpFile=" + unlinkTmpFile
        + " does not end with " + DatanodeUtil.UNLINK_BLOCK_SUFFIX);
  }
  final int n = name.length() - DatanodeUtil.UNLINK_BLOCK_SUFFIX.length(); 
  return new File(unlinkTmpFile.getParentFile(), name.substring(0, n));
}
 
Example 8
Source File: FileExplorerActivity.java    From 920-text-editor-v2 with Apache License 2.0 5 votes vote down vote up
private void onSave() {
    String fileName = binding.filenameEditText.getText().toString().trim();
    if(TextUtils.isEmpty(fileName)) {
        binding.filenameEditText.setError(getString(R.string.can_not_be_empty));
        return;
    }
    if(IOUtils.isInvalidFilename(fileName)) {
        binding.filenameEditText.setError(getString(R.string.illegal_filename));
        return;
    }
    if(TextUtils.isEmpty(lastPath)) {
        binding.filenameEditText.setError(getString(R.string.unknown_path));
        return;
    }

    File f = new File(lastPath);
    if(f.isFile()) {
        f = f.getParentFile();
    }

    final File newFile = new File(f, fileName);
    if (newFile.exists()) {
        UIUtils.showConfirmDialog(getContext(), getString(R.string.override_file_prompt, fileName), new UIUtils.OnClickCallback() {
            @Override
            public void onOkClick() {
                saveAndFinish(newFile);
            }
        });
    } else {
        saveAndFinish(newFile);
    }
}
 
Example 9
Source File: Launcher.java    From knox with Apache License 2.0 5 votes vote down vote up
private static File calcLauncherDir( URL libUrl ) throws UnsupportedEncodingException {
  String libPath = URLDecoder.decode(libUrl.getFile(), StandardCharsets.UTF_8.name());
  File libFile = new File( libPath );
  File dir;
  if( libFile.isDirectory() ) {
    dir = libFile;
  } else {
    dir = libFile.getParentFile();
  }
  return dir;
}
 
Example 10
Source File: PersistentUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean deleteWithRenamingAllFilesStartingWith(@Nonnull File baseFile) {
  File parentFile = baseFile.getParentFile();
  if (parentFile == null) return false;

  File[] files = parentFile.listFiles(pathname -> pathname.getName().startsWith(baseFile.getName()));
  if (files == null) return true;

  boolean deleted = true;
  for (File f : files) {
    deleted &= FileUtil.deleteWithRenaming(f);
  }
  return deleted;
}
 
Example 11
Source File: DataFileIndex.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
DataFileIndexVersion1(File dataIndexFile, String dataFilePrefix) throws IOException {
  mDataFilePrefix = dataFilePrefix;
  mDir = dataIndexFile.getParentFile();
  if (dataIndexFile.exists()) {
    try (RandomAccessFile indexRAF = new RandomAccessFile(dataIndexFile, "r")) {
      final byte[] tempData = new byte[(int) indexRAF.length()];
      indexRAF.readFully(tempData);
      try {
        mIndex = ByteArrayIOUtils.convertToLongArray(tempData); //new long[(int) (mIndexRAF.length() / 8)];
      } catch (final IllegalArgumentException e) {
        throw new CorruptSdfException(mDir);
      }
      long count = 0;
      for (final long i : mIndex) {
        if (i < 0) {
          throw new CorruptSdfException(mDir);
        }
        count += i;
      }
      mTotal = count;
    }
  } else {
    mIndex = new long[0];
    mTotal = 0;
  }

}
 
Example 12
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
static void writeEsriShapefile(Class<?> geomType, List<SimpleFeature> features, File file) throws IOException {
    String geomName = geomType.getSimpleName();
    String basename = file.getName();
    if (basename.endsWith(FILE_EXTENSION_SHAPEFILE)) {
        basename = basename.substring(0, basename.length() - 4);
    }
    File file1 = new File(file.getParentFile(), basename + "_" + geomName + FILE_EXTENSION_SHAPEFILE);

    SimpleFeature simpleFeature = features.get(0);
    SimpleFeatureType simpleFeatureType = changeGeometryType(simpleFeature.getType(), geomType);

    ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
    Map<String, Serializable> map = Collections.singletonMap("url", file1.toURI().toURL());
    ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(map);
    dataStore.createSchema(simpleFeatureType);
    String typeName = dataStore.getTypeNames()[0];
    SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
    DefaultTransaction transaction = new DefaultTransaction("X");
    if (featureSource instanceof SimpleFeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
        SimpleFeatureCollection collection = new ListFeatureCollection(simpleFeatureType, features);
        featureStore.setTransaction(transaction);
        // I'm not sure why the next line is necessary (mp/20170627)
        // Without it is not working, the wrong feature type is used for writing
        // But it is not mentioned in the tutorials
        dataStore.getEntry(featureSource.getName()).getState(transaction).setFeatureType(simpleFeatureType);
        try {
            featureStore.addFeatures(collection);
            transaction.commit();
        } catch (Exception problem) {
            transaction.rollback();
            throw new IOException(problem);
        } finally {
            transaction.close();
        }
    } else {
        throw new IOException(typeName + " does not support read/write access");
    }
}
 
Example 13
Source File: MetaDataParser.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Guesses the album for the given file.
 */
public String guessAlbum(File file, String artist) {
    File parent = file.getParentFile();
    String album = isRoot(parent) ? null : parent.getName();
    if (artist != null && album != null) {
        album = album.replace(artist + " - ", "");
    }
    return album;
}
 
Example 14
Source File: MergeJavaResourcesTask.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void createParentFolderIfNecessary(@NonNull File outputFile) {
    File parentFolder = outputFile.getParentFile();
    if (!parentFolder.exists()) {
        if (!parentFolder.mkdirs()) {
            throw new RuntimeException("Cannot create folder " + parentFolder);
        }
    }
}
 
Example 15
Source File: RelativeFileNameTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private List<String> splitPath(String path) {
    File pathFile = new File(path);
    List<String> split = new LinkedList<String>();
    while (pathFile != null) {
        split.add(0, pathFile.getName());
        pathFile = pathFile.getParentFile();
    }
    return split;
}
 
Example 16
Source File: ServiceDialog.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public void approveSelection() {
    File selected = getSelectedFile();
    boolean exists;

    try {
        exists = selected.exists();
    } catch (SecurityException e) {
        exists = false;
    }

    if (exists) {
        int val;
        val = JOptionPane.showConfirmDialog(this,
                                            getMsg("dialog.overwrite"),
                                            getMsg("dialog.owtitle"),
                                            JOptionPane.YES_NO_OPTION);
        if (val != JOptionPane.YES_OPTION) {
            return;
        }
    }

    try {
        if (selected.createNewFile()) {
            selected.delete();
        }
    }  catch (IOException ioe) {
        JOptionPane.showMessageDialog(this,
                           getMsg("dialog.writeerror")+" "+selected,
                           getMsg("dialog.owtitle"),
                           JOptionPane.WARNING_MESSAGE);
        return;
    } catch (SecurityException se) {
        //There is already file read/write access so at this point
        // only delete access is denied.  Just ignore it because in
        // most cases the file created in createNewFile gets
        // overwritten anyway.
    }
    File pFile = selected.getParentFile();
    if ((selected.exists() &&
              (!selected.isFile() || !selected.canWrite())) ||
             ((pFile != null) &&
              (!pFile.exists() || (pFile.exists() && !pFile.canWrite())))) {
        JOptionPane.showMessageDialog(this,
                           getMsg("dialog.writeerror")+" "+selected,
                           getMsg("dialog.owtitle"),
                           JOptionPane.WARNING_MESSAGE);
        return;
    }

    super.approveSelection();
}
 
Example 17
Source File: OutputPathOption.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
public static ValidationResult validateInputsAndOutputPaths(Collection inputPaths, Path outputPath)
{

    if (inputPaths == null)
    {
        return new ValidationResult(ValidationResult.Level.ERROR, "Input path must be specified.");
    }
    
    if (inputPaths.isEmpty())
    {
        return new ValidationResult(ValidationResult.Level.ERROR, "Couldn't find any application at the root level of the directory. Use `--sourceMode` if the directory contains source files you want to analyse.");
    }

    if (outputPath == null)
    {
        return new ValidationResult(ValidationResult.Level.ERROR, "Output path must be specified.");
    }

    File outputFile = outputPath.toFile();

    boolean nonNullInputFound = false;
    for (Object inputPath : inputPaths)
    {
        File inputFile = (inputPath instanceof Path) ? ((Path)inputPath).toFile() : (File) inputPath;
        if (inputFile == null)
        {
            continue;
        }

        if (inputFile.equals(outputFile))
        {
            return new ValidationResult(ValidationResult.Level.ERROR, "Output file cannot be the same as the input file.");
        }

        File inputParent = inputFile.getParentFile();
        while (inputParent != null)
        {
            if (inputParent.equals(outputFile))
            {
                return new ValidationResult(ValidationResult.Level.ERROR, "Output path must not be a parent of input path.");
            }
            inputParent = inputParent.getParentFile();
        }

        File outputParent = outputFile.getParentFile();
        while (outputParent != null)
        {
            if (outputParent.equals(inputFile))
            {
                return new ValidationResult(ValidationResult.Level.ERROR, "Input path must not be a parent of output path.");
            }
            outputParent = outputParent.getParentFile();
        }
        nonNullInputFound = true;
    }

    if (!nonNullInputFound)
    {
        return new ValidationResult(ValidationResult.Level.ERROR, "Input path must be specified.");
    }


    return ValidationResult.SUCCESS;
}
 
Example 18
Source File: DatabaseRenamer.java    From dhis2-android-sdk with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
boolean renameDatabase(String from, String to) {
    File fromFile = context.getDatabasePath(from);
    File toFile = new File(fromFile.getParentFile(), to);
    return fromFile.renameTo(toFile);
}
 
Example 19
Source File: FileChooser.java    From SikuliNG with MIT License 4 votes vote down vote up
private File showFileChooser(int type, String title, int mode, Object... filters) {
  if (SX.isNotSet(title)) {
    if (SX.isNotSet(this.title)) {
      title = "Select file or folder";
    }
  }
  String last_dir;
  if (SX.isNotNull(folder)) {
    last_dir = folder.getAbsolutePath();
  } else {
    last_dir = SX.getOption("LAST_OPEN_DIR", "NotSet");
  }
  log.debug("showFileChooser: %s at %s", title.split(" ")[0], last_dir);
  JFileChooser fchooser = null;
  File fileChoosen = null;
  while (true) {
    fchooser = new JFileChooser();
    if (SX.isMac()) {
      fchooser.putClientProperty("JFileChooser.packageIsTraversable", "always");
    }
    if (!"NotSet".equals(last_dir)) {
      fchooser.setCurrentDirectory(new File(last_dir));
    }
    fchooser.setSelectedFile(null);
    if (SX.isMac() && type == DIRS) {
      fchooser.setFileSelectionMode(DIRSANDFILES);
    } else {
      fchooser.setFileSelectionMode(type);
    }
    fchooser.setDialogTitle(title);
    String btnApprove = "Select";
    if (mode == FileDialog.SAVE) {
      fchooser.setDialogType(JFileChooser.SAVE_DIALOG);
      btnApprove = "Save";
    }
    if (SX.isNull(filters) || filters.length == 0) {
      fchooser.setAcceptAllFileFilterUsed(true);
    } else {
      fchooser.setAcceptAllFileFilterUsed(false);
      for (Object filter : filters) {
        if (filter instanceof SikulixFileFilter) {
          fchooser.addChoosableFileFilter((SikulixFileFilter) filter);
        } else {
          fchooser.setFileFilter((FileNameExtensionFilter) filter);
          checkSikuli = false;
        }
      }
    }
    if (fchooser.showDialog(parent, btnApprove) != JFileChooser.APPROVE_OPTION) {
      return null;
    }
    fileChoosen = fchooser.getSelectedFile();
    if (mode == FileDialog.LOAD) {
      if (checkSikuli && !isValidScript(fileChoosen)) {
        // folders must contain a valid scriptfile
        Do.popError("Folder not a valid SikuliX script\nTry again.");
        last_dir = fileChoosen.getAbsolutePath();
        continue;
      }
      break;
    }
  }
  File selected = new File(fileChoosen.getAbsolutePath());
  if (!selected.isDirectory() || type == DIRS) {
    selected = selected.getParentFile();
  }
  SX.setOption("LAST_OPEN_DIR", selected.getAbsolutePath());
  return fileChoosen;
}
 
Example 20
Source File: DependencyNode.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public File getJavadocFile() {
    File artifact = art.getFile();
    String version = artifact.getParentFile().getName();
    String artifactId = artifact.getParentFile().getParentFile().getName();
    return new File(artifact.getParentFile(), artifactId + "-" + version + (art.getClassifier() != null ? ("tests".equals(art.getClassifier()) ? "-test" : "-" + art.getClassifier()) : "") + "-javadoc.jar"); //NOI18N
}