java.nio.file.Files类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(11.1k)|赞(0)|评价(0)|浏览(306)

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

Files介绍

暂无

代码示例

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

static Collection<String> getLocalizedUsers(Path localBaseDir) throws IOException {
  Path userCacheDir = getUserCacheDir(localBaseDir);
  if (!Files.exists(userCacheDir)) {
    return Collections.emptyList();
  }
  return Files.list(userCacheDir).map((p) -> p.getFileName().toString()).collect(Collectors.toList());
}

代码示例来源:origin: siacs/Conversations

@Override
public final void forEach(final BiConsumer<? super String, ? super byte[]> action) {
  if (Files.exists(cacheDirectory))
    try (final Stream<Path> files = cacheContent().filter(Files::isReadable)) {
      files.forEach(file -> {
        try {
          action.accept(file.getFileName().toString(), Files.readAllBytes(file));
        } catch (final IOException e) {
          throw new UncheckedIOException(e);
        }
      });
    }
}

代码示例来源:origin: prestodb/presto

public static void writePluginServices(Iterable<String> plugins, File root)
    throws IOException
{
  Path path = root.toPath().resolve(SERVICES_FILE);
  createDirectories(path.getParent());
  try (Writer out = new OutputStreamWriter(new FileOutputStream(path.toFile()), UTF_8)) {
    for (String plugin : plugins) {
      out.write(plugin + "\n");
    }
  }
}

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

/**
 * This implementation checks whether the underlying file is marked as readable
 * (and corresponds to an actual file with content, not to a directory).
 * @see java.nio.file.Files#isReadable(Path)
 * @see java.nio.file.Files#isDirectory(Path, java.nio.file.LinkOption...)
 */
@Override
public boolean isReadable() {
  return (Files.isReadable(this.path) && !Files.isDirectory(this.path));
}

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

/**
 * This implementation checks whether the underlying file is marked as writable
 * (and corresponds to an actual file with content, not to a directory).
 * @see java.io.File#canWrite()
 * @see java.io.File#isDirectory()
 */
@Override
public boolean isWritable() {
  return (this.file != null ? this.file.canWrite() && !this.file.isDirectory() :
      Files.isWritable(this.filePath) && !Files.isDirectory(this.filePath));
}

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

/**
 * This implementation opens a OutputStream for the underlying file.
 * @see java.nio.file.spi.FileSystemProvider#newOutputStream(Path, OpenOption...)
 */
@Override
public OutputStream getOutputStream() throws IOException {
  if (Files.isDirectory(this.path)) {
    throw new FileNotFoundException(getPath() + " (is a directory)");
  }
  return Files.newOutputStream(this.path);
}

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

private List<URL> buildClasspath(List<String> jars) throws IOException {
 List<URL> urls = new ArrayList<>();
 for (String jar : jars) {
  Path jarPath = Paths.get(jar);
  if (Files.isDirectory(jarPath)) {
   try (Stream<Path> stream = Files.list(jarPath)) {
    List<Path> files = stream
      .filter((path) -> Files.isRegularFile(path))
      .collect(Collectors.toList());
    for (Path file : files) {
     URL url = file.toUri().toURL();
     urls.add(url);
    }
   }
  } else {
   URL url = jarPath.toUri().toURL();
   urls.add(url);
  }
 }
 return urls;
}

代码示例来源:origin: real-logic/agrona

private static void expandPrimitiveSpecialisedClass(final String packageName, final String className)
  throws IOException
{
  final Path inputPath = Paths.get(SOURCE_DIRECTORY, packageName, className + SUFFIX);
  final Path outputDirectory = Paths.get(GENERATED_DIRECTORY, packageName);
  Files.createDirectories(outputDirectory);
  final List<String> contents = Files.readAllLines(inputPath, UTF_8);
  for (final Substitution substitution : SUBSTITUTIONS)
  {
    final String substitutedFileName = substitution.substitute(className);
    final List<String> substitutedContents = contents
      .stream()
      .map(substitution::checkedSubstitute)
      .collect(toList());
    final Path outputPath = Paths.get(GENERATED_DIRECTORY, packageName, substitutedFileName + SUFFIX);
    Files.write(outputPath, substitutedContents, UTF_8);
  }
}

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

public void appendConfiguration(Configuration config) throws IOException {
  final Configuration mergedConfig = new Configuration();
  mergedConfig.addAll(defaultConfig);
  mergedConfig.addAll(config);
  final List<String> configurationLines = mergedConfig.toMap().entrySet().stream()
    .map(entry -> entry.getKey() + ": " + entry.getValue())
    .collect(Collectors.toList());
  Files.write(conf.resolve("flink-conf.yaml"), configurationLines);
}

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

private static void createHtmlFile(DocumentingRestEndpoint restEndpoint, RestAPIVersion apiVersion, Path outputFile) throws IOException {
  StringBuilder html = new StringBuilder();
  List<MessageHeaders> specs = restEndpoint.getSpecs().stream()
    .filter(spec -> spec.getSupportedAPIVersions().contains(apiVersion))
    .collect(Collectors.toList());
  specs.forEach(spec -> html.append(createHtmlEntry(spec)));
  Files.deleteIfExists(outputFile);
  Files.write(outputFile, html.toString().getBytes(StandardCharsets.UTF_8));
}

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

private static List<Path> listRecursively(final Path dir) {
    try {
      if (!Files.exists(dir)) {
        return Collections.emptyList();
      } else {
        try (Stream<Path> files = Files.walk(dir, FileVisitOption.FOLLOW_LINKS)) {
          return files.filter(Files::isRegularFile).collect(Collectors.toList());
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}

代码示例来源:origin: jooby-project/jooby

private void onSyncPackageJson(Config conf, Path workDirectory, Throwing.Consumer<String> action)
  throws IOException {
 Path tmp = Paths.get(conf.getString("application.tmpdir"), "package.json");
 Files.createDirectories(tmp);
 String sha1 = Hashing.sha256()
   .hashBytes(Files.readAllBytes(workDirectory.resolve("package.json")))
   .toString();
 Path lastSha1 = tmp.resolve(sha1);
 if (!Files.exists(lastSha1) || !Files.exists(workDirectory.resolve("node_modules"))) {
  action.accept("install");
  Try.of(Files.walk(tmp))
    .run(files -> files.filter(f -> !f.equals(tmp)).forEach(throwingConsumer(Files::deleteIfExists)));
  Files.write(tmp.resolve(lastSha1), Arrays.asList(""));
 }
}

代码示例来源:origin: twosigma/beakerx

private void handleClasspathAddMvnDep(String allCode, String expected) throws Exception {
 MagicCommand command = new MagicCommand(new ClasspathAddMvnMagicCommand(configuration.mavenResolverParam(kernel), kernel), allCode);
 Code code = Code.createCode(allCode, singletonList(command), NO_ERRORS, new Message(new Header(JupyterMessages.COMM_MSG, "session1")));
 //when
 code.execute(kernel, 1);
 //then
 Optional<Message> updateMessage = EvaluatorResultTestWatcher.waitForUpdateMessage(kernel);
 String text = (String) TestWidgetUtils.getState(updateMessage.get()).get("value");
 assertThat(text).contains(expected);
 String mvnDir = kernel.getTempFolder().toString() + MavenJarResolver.MVN_DIR;
 Stream<Path> paths = Files.walk(Paths.get(mvnDir));
 Optional<Path> dep = paths.filter(file -> (file.getFileName().toFile().getName().contains("gson") ||
     file.getFileName().toFile().getName().contains("slf4j"))).findFirst();
 assertThat(dep).isPresent();
 assertThat(kernel.getClasspath().get(0)).contains(mvnDir);
 assertThat(Files.exists(Paths.get(configuration.mavenResolverParam(kernel).getPathToNotebookJars() + File.separator + MAVEN_BUILT_CLASSPATH_FILE_NAME))).isTrue();
 dep.ifPresent(path -> {
  try {
   FileUtils.forceDelete(path.toFile());
  } catch (IOException e) {
   e.printStackTrace();
  }
 });
}

代码示例来源:origin: twosigma/beakerx

protected static byte[] getBytes(Object data) throws IOException {
 byte[] bytes;
 if (isValidURL(data.toString())) {
  bytes = ByteStreams.toByteArray((new URL(data.toString()).openStream()));
 } else if (exists(data.toString())) {
  Path path = Paths.get(data.toString());
  bytes = Files.readAllBytes(path);
 } else {
  throw new FileNotFoundException(data.toString() + " doesn't exist. ");
 }
 return bytes;
}

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

public void copyOptJarsToLib(String jarNamePrefix) throws FileNotFoundException, IOException {
  final Optional<Path> reporterJarOptional;
  try (Stream<Path> logFiles = Files.walk(opt)) {
    reporterJarOptional = logFiles
      .filter(path -> path.getFileName().toString().startsWith(jarNamePrefix))
      .findFirst();
  }
  if (reporterJarOptional.isPresent()) {
    final Path optReporterJar = reporterJarOptional.get();
    final Path libReporterJar = lib.resolve(optReporterJar.getFileName());
    Files.copy(optReporterJar, libReporterJar);
    filesToDelete.add(new AutoClosablePath(libReporterJar));
  } else {
    throw new FileNotFoundException("No jar could be found matching the pattern " + jarNamePrefix + ".");
  }
}

代码示例来源:origin: prestodb/presto

@Test
public void testCreateWithNonexistentStagingDirectory()
    throws Exception
{
  java.nio.file.Path stagingParent = createTempDirectory("test");
  java.nio.file.Path staging = Paths.get(stagingParent.toString(), "staging");
  // stagingParent = /tmp/testXXX
  // staging = /tmp/testXXX/staging
  try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
    MockAmazonS3 s3 = new MockAmazonS3();
    Configuration conf = new Configuration();
    conf.set(S3_STAGING_DIRECTORY, staging.toString());
    fs.initialize(new URI("s3n://test-bucket/"), conf);
    fs.setS3Client(s3);
    FSDataOutputStream stream = fs.create(new Path("s3n://test-bucket/test"));
    stream.close();
    assertTrue(Files.exists(staging));
  }
  finally {
    deleteRecursively(stagingParent, ALLOW_INSECURE);
  }
}

代码示例来源:origin: org.apache.ant/ant

/** Load the property files specified by -propertyfile */
private void loadPropertyFiles() {
  for (final String filename : propertyFiles) {
    final Properties props = new Properties();
    InputStream fis = null;
    try {
      fis = Files.newInputStream(Paths.get(filename));
      props.load(fis);
    } catch (final IOException e) {
      System.out.println("Could not load property file "
                + filename + ": " + e.getMessage());
    } finally {
      FileUtils.close(fis);
    }
    // ensure that -D properties take precedence
    props.stringPropertyNames().stream()
        .filter(name -> definedProps.getProperty(name) == null)
        .forEach(name -> definedProps.put(name, props.getProperty(name)));
  }
}

代码示例来源:origin: jooby-project/jooby

private String packageJson(File[] cp) {
 if (Files.exists(Paths.get("package.json"))) {
  return Arrays.asList(cp).stream()
    .filter(f -> f.getAbsolutePath().contains("jooby-frontend"))
    .findFirst()
    .map(f -> File.pathSeparator + "package.json")
    .orElse("");
 }
 return "";
}

代码示例来源:origin: SonarSource/sonarqube

@Test
public void test_content() throws IOException {
 Path testFile = baseDir.resolve(PROJECT_RELATIVE_PATH);
 Files.createDirectories(testFile.getParent());
 String content = "test é string";
 Files.write(testFile, content.getBytes(StandardCharsets.ISO_8859_1));
 assertThat(Files.readAllLines(testFile, StandardCharsets.ISO_8859_1).get(0)).hasSize(content.length());
 Metadata metadata = new Metadata(42, 30, "", new int[0], new int[0], 10);
 DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata))
  .setStatus(InputFile.Status.ADDED)
  .setCharset(StandardCharsets.ISO_8859_1);
 assertThat(inputFile.contents()).isEqualTo(content);
 try (InputStream inputStream = inputFile.inputStream()) {
  String result = new BufferedReader(new InputStreamReader(inputStream, inputFile.charset())).lines().collect(Collectors.joining());
  assertThat(result).isEqualTo(content);
 }
}

代码示例来源:origin: org.apache.logging.log4j/log4j-core

private Path writeTextTo(final String location) throws IOException {
    final Path path = Paths.get(location);
    Files.createDirectories(path.getParent());
    try (BufferedWriter buffy = Files.newBufferedWriter(path, Charset.defaultCharset())) {
      buffy.write("some text");
      buffy.newLine();
      buffy.flush();
    }
    return path;
  }
}

相关文章

微信公众号

最新文章

更多