java.io.File.getParent()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.6k)|赞(0)|评价(0)|浏览(152)

本文整理了Java中java.io.File.getParent()方法的一些代码示例,展示了File.getParent()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.getParent()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:getParent

File.getParent介绍

[英]Returns the pathname of the parent of this file. This is the path up to but not including the last name. null is returned if there is no parent.
[中]返回此文件父级的路径名。这是到达但不包括姓氏的路径。如果没有父级,则返回null。

代码示例

代码示例来源:origin: neo4j/neo4j

/**
 * This is used by different flavors of file repositories to agree on a naming convention
 * for repository files that are renamed after migration to prevent accidental reuse.
 */
static File getMigratedFile( File file )
{
  return new File( file.getParent(), file.getName() + ".migrated" );
}

代码示例来源:origin: redisson/redisson

/**
 * {@inheritDoc}
 */
public Sink write(Manifest manifest) throws IOException {
  if (manifest != null) {
    File target = new File(folder, JarFile.MANIFEST_NAME);
    if (!target.getParentFile().isDirectory() && !target.getParentFile().mkdirs()) {
      throw new IOException("Could not create directory: " + target.getParent());
    }
    OutputStream outputStream = new FileOutputStream(target);
    try {
      manifest.write(outputStream);
    } finally {
      outputStream.close();
    }
  }
  return this;
}

代码示例来源:origin: android-hacker/VirtualXposed

public static boolean isSymlink(File file) throws IOException {
  if (file == null)
    throw new NullPointerException("File must not be null");
  File canon;
  if (file.getParent() == null) {
    canon = file;
  } else {
    File canonDir = file.getParentFile().getCanonicalFile();
    canon = new File(canonDir, file.getName());
  }
  return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

代码示例来源:origin: querydsl/querydsl

private Writer writerFor(File file) {
  if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
    System.err.println("Folder " + file.getParent() + " could not be created");
  }
  try {
    return new OutputStreamWriter(new FileOutputStream(file), charset);
  } catch (FileNotFoundException e) {
    throw new RuntimeException(e.getMessage(), e);
  }
}

代码示例来源:origin: libgdx/libgdx

public FileHandle sibling (String name) {
  name = name.replace('\\', '/');
  if (file.getPath().length() == 0) throw new GdxRuntimeException("Cannot get the sibling of the root.");
  return Gdx.files.getFileHandle(new File(file.getParent(), name).getPath(), type); //this way we can find the sibling even if it's inside the obb
}

代码示例来源:origin: mpetazzoni/ttorrent

public static FileCollectionStorage create(TorrentMetadata metadata, File parent) throws IOException {
 if (!parent.isDirectory()) {
  throw new IllegalArgumentException("Invalid parent directory!");
 }
 List<FileStorage> files = new LinkedList<FileStorage>();
 long offset = 0L;
 long totalSize = 0;
 for (TorrentFile file : metadata.getFiles()) {
  File actual = new File(parent, file.getRelativePathAsString());
  if (!actual.getCanonicalPath().startsWith(parent.getCanonicalPath())) {
   throw new SecurityException("Torrent file path attempted " +
       "to break directory jail!");
  }
  if (!actual.getParentFile().exists() && !actual.getParentFile().mkdirs()) {
   throw new IOException("Unable to create directories " + actual.getParent() + " for storing torrent file " + actual.getName());
  }
  files.add(new FileStorage(actual, offset, file.size));
  offset += file.size;
  totalSize += file.size;
 }
 return new FileCollectionStorage(files, totalSize);
}

代码示例来源:origin: Netflix/Priam

public File createTmpMetaFile() throws IOException {
  File metafile = File.createTempFile("meta", ".json");
  File destFile = new File(metafile.getParent(), "meta.json");
  if (destFile.exists()) destFile.delete();
  FileUtils.moveFile(metafile, destFile);
  return destFile;
}

代码示例来源:origin: simpligility/android-maven-plugin

/**
 * @return the path to the dx.jar
 */
public String getD8JarPath()
{
  final File pathToDexJar = new File( getPathForBuildTool( BuildToolInfo.PathId.DX_JAR ) );
  final File pathToD8Jar = new File( pathToDexJar.getParent(), "d8.jar" );
  return pathToD8Jar.getAbsolutePath();
}

代码示例来源:origin: ming1016/study

public void analyze(String path) {
  String upath = _.unifyPath(path);
  File f = new File(upath);
  projectDir = f.isDirectory() ? f.getPath() : f.getParent();
  loadFileRecursive(upath);
}

代码示例来源:origin: lingochamp/okdownload

@Test
public void getStatus() throws IOException {
  file.getParentFile().mkdirs();
  file.createNewFile();
  assertThat(file.exists()).isTrue();
  StatusUtil.Status status = StatusUtil
      .getStatus(url, file.getParent(), file.getName());
  assertThat(status).isEqualTo(COMPLETED);
  // no filename
  status = StatusUtil.getStatus(url, file.getParentFile().getPath(), null);
  assertThat(status).isEqualTo(UNKNOWN);
  final DownloadDispatcher dispatcher = OkDownload.with().downloadDispatcher();
  doReturn(true).when(dispatcher).isRunning(any(DownloadTask.class));
  status = StatusUtil.getStatus(url, file.getParentFile().getPath(), null);
  assertThat(status).isEqualTo(RUNNING);
  doReturn(true).when(dispatcher).isPending(any(DownloadTask.class));
  status = StatusUtil.getStatus(url, file.getParentFile().getPath(), null);
  assertThat(status).isEqualTo(PENDING);
}

代码示例来源:origin: oracle/opengrok

@Override
public boolean fileHasHistory(File file) {
  String parentFile = file.getParent();
  String name = file.getName();
  File f = Paths.get(parentFile, "SCCS", "s." + name).toFile();
  return f.exists();
}

代码示例来源:origin: spring-projects/spring-batch

@Test
public void testOpenWithNonWritableFile() throws Exception {
  writer = new FlatFileItemWriter<>();
  writer.setLineAggregator(new PassThroughLineAggregator<>());
  FileSystemResource file = new FileSystemResource("build/no-such-file.foo");
  writer.setResource(file);
  new File(file.getFile().getParent()).mkdirs();
  file.getFile().createNewFile();
  assertTrue("Test file must exist: " + file, file.exists());
  assertTrue("Test file set to read-only: " + file, file.getFile().setReadOnly());
  assertFalse("Should be readonly file: " + file, file.getFile().canWrite());
  writer.afterPropertiesSet();
  try {
    writer.open(executionContext);
    fail("Expected IllegalStateException");
  }
  catch (IllegalStateException e) {
    String message = e.getMessage();
    assertTrue("Message does not contain 'writable': " + message, message.indexOf("writable") >= 0);
  }
}

代码示例来源:origin: kiegroup/optaplanner

@Override
public int compare(File a, File b) {
  String aLowerCaseName = a.getName().toLowerCase(Locale.US);
  String bLowerCaseName = b.getName().toLowerCase(Locale.US);
  return new CompareToBuilder()
      .append(a.getParent(), b.getParent(), ALPHA_NUMERIC_STRING_COMPARATOR)
      .append(a.isDirectory(), b.isDirectory())
      .append(!aLowerCaseName.startsWith("demo"), !bLowerCaseName.startsWith("demo"))
      .append(aLowerCaseName, bLowerCaseName, ALPHA_NUMERIC_STRING_COMPARATOR)
      .append(a.getName(), b.getName())
      .toComparison();
}

代码示例来源:origin: checkstyle/checkstyle

/**
 * Retrieves the folder path from the given {@code file}.
 *
 * @param file Input file to examine.
 * @return The folder path.
 * @throws CheckstyleException if there is an error getting the canonical
 *         path of the {@code file}.
 */
private static String getFolderPath(File file) throws CheckstyleException {
  try {
    return file.getCanonicalFile().getParent();
  }
  catch (IOException ex) {
    throw new CheckstyleException("unable to create canonical path names for "
        + file.getAbsolutePath(), ex);
  }
}

代码示例来源:origin: syncany/syncany

@Test
public void testExecuteAdd() throws Exception {
  when(options.getAction()).thenReturn(DaemonAction.ADD);
  List<String> watchRoots = new ArrayList<String>();
  watchRoots.add(tempWatchRootAppFolder.getParent());
  when(options.getWatchRoots()).thenReturn(watchRoots);
  DaemonOperationResult res = deamonOp.execute();
  assertNotNull(res);
  assertEquals(DaemonResultCode.OK, res.getResultCode());
  assertNotNull(res.getWatchList());
  assertEquals(1, res.getWatchList().size());
  assertEquals(tempWatchRootAppFolder.getParentFile().getAbsolutePath(), res.getWatchList().get(0).getPath());
}

代码示例来源:origin: apache/zookeeper

public static JFile parseFile(File file) throws FileNotFoundException, ParseException {
  curDir = file.getParent();
  curFileName = file.getName();
  FileReader reader = new FileReader(file);
  try {
    Rcc parser = new Rcc(reader);
    recTab = new Hashtable<String, JRecord>();
    return parser.Input();
  } finally {
    try {
      reader.close();
    } catch (IOException e) {
    }
  }
}

代码示例来源:origin: languagetool-org/languagetool

public BerkeleyLanguageModel(File berkeleyLm) {
 if (!berkeleyLm.isFile()) {
  throw new RuntimeException("You need to specify a BerkeleyLM file (*.blm.gz): " + berkeleyLm);
 }
 File vocabFile = new File(berkeleyLm.getParent(), "vocab_cs.gz");
 if (!vocabFile.exists()) {
  throw new RuntimeException("No vocabulary file 'vocab_cs.gz' found in the BerkeleyLM directory: " + vocabFile);
 }
 lm = LmReaders.readGoogleLmBinary(berkeleyLm.getAbsolutePath(), vocabFile.getAbsolutePath());
}

代码示例来源:origin: libgdx/libgdx

public FileHandle sibling (String name) {
  name = name.replace('\\', '/');
  if (file.getPath().length() == 0) throw new GdxRuntimeException("Cannot get the sibling of the root.");
  return Gdx.files.getFileHandle(new File(file.getParent(), name).getPath(), type); //this way we can find the sibling even if it's inside the obb
}

代码示例来源:origin: redisson/redisson

/**
 * {@inheritDoc}
 */
public void store(Map<TypeDescription, byte[]> binaryRepresentations) throws IOException {
  for (Map.Entry<TypeDescription, byte[]> entry : binaryRepresentations.entrySet()) {
    File target = new File(folder, entry.getKey().getInternalName() + CLASS_FILE_EXTENSION);
    if (!target.getParentFile().isDirectory() && !target.getParentFile().mkdirs()) {
      throw new IOException("Could not create directory: " + target.getParent());
    }
    OutputStream outputStream = new FileOutputStream(target);
    try {
      outputStream.write(entry.getValue());
    } finally {
      outputStream.close();
    }
  }
}

代码示例来源:origin: Meituan-Dianping/walle

public static File removeDirInvalidChar(final File file) {
    if (System.getProperties().getProperty("os.name").toUpperCase().startsWith("WINDOWS")) {
      final String newFileName = file.getName().replaceAll("\"", "");
      return new File(file.getParent(), newFileName);
    }
    return file;
  }
}

相关文章