java.nio.file.Files.write()方法的使用及代码示例

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

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

Files.write介绍

暂无

代码示例

代码示例来源:origin: apache/incubator-druid

public File createDescriptorFile(final ObjectMapper jsonMapper, final DataSegment segment)
  throws IOException
{
 File descriptorFile = File.createTempFile("descriptor", ".json");
 // Avoid using Guava in DataSegmentPushers because they might be used with very diverse Guava versions in
 // runtime, and because Guava deletes methods over time, that causes incompatibilities.
 Files.write(descriptorFile.toPath(), jsonMapper.writeValueAsBytes(segment));
 return descriptorFile;
}

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

private void writeReadMe() throws IOException {
 String text =
   "This directory contains a backup of the persistent data for a single gemfire VM. The layout is:diskstoresA backup of the persistent disk stores in the VMuserAny files specified by the backup element in the cache.xml file.configThe cache.xml and gemfire.properties for the backed up member.restore.[sh|bat]A script to restore the backup.Please note that the config is not restored, only the diskstores and user files.";
 Files.write(backupDirectory.resolve(README_FILE), text.getBytes());
}

代码示例来源:origin: blynkkk/blynk-server

public boolean writeCloneProjectToDisk(String token, String json) {
  try {
    Path path = Paths.get(cloneDataDir, token);
    Files.write(path, json.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
    return true;
  } catch (Exception e) {
    log.error("Error saving cloned project to disk. {}", e.getMessage());
  }
  return false;
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testResolveFileFromDifferentThreads() throws Exception {
 int size = 10 * 1024 * 1024;
 new Random().nextBytes(content);
 File out = new File("target/test-classes/temp");
 if (out.exists()) {
  Files.delete(out.toPath());
 Files.write(out.toPath(), content, StandardOpenOption.CREATE_NEW);
    start.await();
    File file = resolver.resolveFile("temp");
    byte[] data = Files.readAllBytes(file.toPath());
    Assert.assertArrayEquals(content, data);
   } catch (Exception e) {

代码示例来源:origin: pxb1988/dex2jar

Path jar = new File(remainingArgs[0]).toPath();
if (!Files.exists(jar)) {
  System.err.println(jar + " is not exists");
    output = new File(jar.getFileName() + "-rechecksum.dex").toPath();
  } else {
    output = new File(getBaseName(jar.getFileName().toString()) + "-rechecksum.dex").toPath();
b.putInt(32, data.length);
DexFileWriter.updateChecksum(b, data.length);
Files.write(output, data);

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

@Test
public void always_try_utf8() throws IOException {
 ByteArrayOutputStream out = new ByteArrayOutputStream();
 // this is a valid 2 byte UTF-8. 
 out.write(194);
 out.write(128);
 Path filePath = temp.newFile().toPath();
 Files.write(filePath, out.toByteArray());
 assertThat(detectCharset(filePath, UTF_16)).isEqualTo(UTF_8);
}

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

private void corruptJar( URL jar ) throws IOException, URISyntaxException
{
  File jarFile = new File( jar.toURI() ).getCanonicalFile();
  long fileLength = jarFile.length();
  byte[] bytes = Files.readAllBytes( Paths.get( jar.toURI() ) );
  for ( long i = fileLength / 2; i < fileLength; i++ )
  {
    bytes[(int) i] = 0;
  }
  Files.write( jarFile.toPath(), bytes );
}

代码示例来源:origin: AdoptOpenJDK/jitwatch

public static boolean fetchJVMS()
{
  String html = NetUtil.fetchURL("https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html");
  String css = NetUtil.fetchURL("https://docs.oracle.com/javase/specs/javaspec.css");
  boolean result = false;
  
  if (html.length() > 0 && css.length() > 0)
  {
    Path pathHTML = Paths.get(new File(JVMS_HTML_FILENAME).toURI());
    Path pathCSS = Paths.get(new File(JVMS_CSS_FILENAME).toURI());
    try
    {
      Files.write(pathHTML, html.getBytes(StandardCharsets.UTF_8));
      Files.write(pathCSS, css.getBytes(StandardCharsets.UTF_8));
      result = true;
    }
    catch (IOException ioe)
    {
      logger.error("Could not save JVMS to disk", ioe);
    }
  }
  return result;
}

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

@Test
public void downloadDirWithChecksum() throws Exception {
  File folder = temporaryFolder.newFolder("log");
  Files.write(Paths.get(folder.getPath(), "a"), "content for a".getBytes());
  Files.write(Paths.get(folder.getPath(), "b"), "content for b".getBytes());
  File zip = new ZipUtil().zip(folder, temporaryFolder.newFile("log.zip"), Deflater.NO_COMPRESSION);
  httpService.setupDownload("http://far.far.away/log.zip", zip);
  httpService.setupDownload("http://far.far.away/log.zip.md5", "s/log/a=524ebd45bd7de3616317127f6e639bd6\ns/log/b=83c0aa3048df233340203c74e8a93d7d");
  runBuild(downloadDir(map(
      "url", "http://far.far.away/log.zip",
      "dest", "dest",
      "src", "s/log",
      "checksumUrl", "http://far.far.away/log.zip.md5")), Passed);
  File dest = new File(sandbox, "dest");
  assertThat(console.output(), containsString(String.format("Saved artifact to [%s] after verifying the integrity of its contents", dest.getPath())));
  assertThat(FileUtils.readFileToString(new File(dest, "log/a"), UTF_8), is("content for a"));
  assertThat(FileUtils.readFileToString(new File(dest, "log/b"), UTF_8), is("content for b"));
}

代码示例来源:origin: googleapis/google-cloud-java

@Test
public void testCopyReplace_targetExists_works() throws Exception {
 Path source = Paths.get(URI.create("gs://military/fashion.show"));
 Path target = Paths.get(URI.create("gs://greenbean/adipose"));
 Files.write(source, "(✿◕ ‿◕ )ノ".getBytes(UTF_8));
 Files.write(target, "(✿◕ ‿◕ )ノ".getBytes(UTF_8));
 Files.copy(source, target, REPLACE_EXISTING);
}

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

@Test
public void shouldBeAbleToAttachToPidAndRunThreadDump() throws IOException, CommandFailed, IncorrectUsage
  Files.createFile( testDirectory.file( "neo4j.conf" ).toPath() );
  Files.write( Paths.get( run.getAbsolutePath(), "neo4j.pid" ), String.valueOf( pid ).getBytes() );
    Path homeDir = testDirectory.directory().toPath();
    DiagnosticsReportCommand diagnosticsReportCommand =
        new DiagnosticsReportCommand( homeDir, homeDir, outsideWorld );
  assertThat( files.length, is( 1 ) );
  Path report = files[0].toPath();
  final URI uri = URI.create( "jar:file:" + report.toUri().getRawPath() );

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

@Test
void shouldRoundTripFilesWithDifferentContent() throws IOException, IncorrectFormat
{
  Path directory = testDirectory.directory( "a-directory" ).toPath();
  Files.createDirectories( directory );
  Files.write( directory.resolve( "a-file" ), "text".getBytes() );
  Files.write( directory.resolve( "another-file" ), "some-different-text".getBytes() );
  assertRoundTrips( directory );
}

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

@Test
public void dontPublishFilesWithoutDetectedLanguage() throws IOException {
 Path mainDir = baseDir.toPath().resolve("src").resolve("main");
 Files.createDirectories(mainDir);
 Path testDir = baseDir.toPath().resolve("src").resolve("test");
 Files.createDirectories(testDir);
 Path testXooFile = testDir.resolve("sample.java");
 Files.write(testXooFile, "Sample xoo\ncontent".getBytes(StandardCharsets.UTF_8));
 Path xooFile = mainDir.resolve("sample.xoo");
 Files.write(xooFile, "Sample xoo\ncontent".getBytes(StandardCharsets.UTF_8));
 Path javaFile = mainDir.resolve("sample.java");
 Files.write(javaFile, "Sample xoo\ncontent".getBytes(StandardCharsets.UTF_8));
 logTester.setLevel(LoggerLevel.DEBUG);
 AnalysisResult result = tester.newAnalysis()
  .properties(builder
   .put("sonar.sources", "src/main")
   .put("sonar.tests", "src/test")
   .build())
  .execute();
 assertThat(logTester.logs()).contains("3 files indexed");
 assertThat(logTester.logs()).contains("'src/main/sample.xoo' generated metadata with charset 'UTF-8'");
 assertThat(logTester.logs().stream().collect(joining("\n"))).doesNotContain("'src/main/sample.java' generated metadata");
 assertThat(logTester.logs().stream().collect(joining("\n"))).doesNotContain("'src/test/sample.java' generated metadata");
 DefaultInputFile javaInputFile = (DefaultInputFile) result.inputFile("src/main/sample.java");
 thrown.expect(IllegalStateException.class);
 thrown.expectMessage("Unable to find report for component");
 result.getReportComponent(javaInputFile);
}

代码示例来源: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

@Test
public void testGetPassword() throws Exception {
  final String PASSWORD = "myPass123";
  final Path path = Files.createTempFile("testPass", ".txt");
  Files.write(path, PASSWORD.getBytes(Charset.defaultCharset()));
  char[] actual = new FilePasswordProvider(path.toString()).getPassword();
  Files.delete(path);
  assertArrayEquals(PASSWORD.toCharArray(), actual);
}

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

@Test
void shouldGiveAClearErrorMessageIfTheDestinationsParentDirectoryIsAFile()
    throws IOException
{
  Path archive = testDirectory.file( "the-archive.dump" ).toPath();
  Path destination = Paths.get( testDirectory.absolutePath().getAbsolutePath(), "subdir", "the-destination" );
  Files.write( destination.getParent(), new byte[0] );
  FileSystemException exception = assertThrows( FileSystemException.class, () -> new Loader().load( archive, destination, destination ) );
  assertEquals( destination.getParent().toString() + ": Not a directory", exception.getMessage() );
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testWatcherPerformances() throws IOException, InterruptedException {
 List<File> files = new ArrayList<>();
    File txt = new File(subsub, k + ".txt");
    files.add(txt);
    Files.write(txt.toPath(), Integer.toString(k).getBytes());
    File java = new File(subsub, k + ".java");
    Files.write(java.toPath(), Integer.toString(k).getBytes());
 Path path = files.get(0).toPath();
 Thread.sleep(1000); // Need to wait to be sure we are not in the same second as the previous write
 Files.write(path, "booooo".getBytes());
 assertWaitUntil(() -> undeploy.get() == 1);
 assertWaitUntil(() -> deploy.get() == 2);
 files.get(1).delete();
 File newFile = new File(root, "test.txt");
 Files.write(newFile.toPath(), "I'm a new file".getBytes());
 assertWaitUntil(() -> undeploy.get() == 3);
 assertWaitUntil(() -> deploy.get() == 4);

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

private File writeYarnPropertiesFile(String contents) throws IOException {
    File tmpFolder = tmp.newFolder();
    String currentUser = System.getProperty("user.name");

    // copy .yarn-properties-<username>
    File testPropertiesFile = new File(tmpFolder, ".yarn-properties-" + currentUser);
    Files.write(testPropertiesFile.toPath(), contents.getBytes(), StandardOpenOption.CREATE);

    return tmpFolder.getAbsoluteFile();
  }
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testRunVerticleWithConfFile() throws Exception {
 Path tempDir = testFolder.newFolder().toPath();
 Path tempFile = Files.createTempFile(tempDir, "conf", "json");
 MyLauncher launcher = new MyLauncher();
 JsonObject conf = new JsonObject().put("foo", "bar").put("wibble", 123);
 Files.write(tempFile, conf.encode().getBytes());
 String[] args = {"run", "java:" + TestVerticle.class.getCanonicalName(), "-conf", tempFile.toString()};
 launcher.dispatch(args);
 assertWaitUntil(() -> TestVerticle.instanceCount.get() == 1);
 assertEquals(conf, TestVerticle.conf);
}

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

private void copyExecutable(String name, File target)
      throws IOException
  {
    byte[] bytes = toByteArray(Resources.getResource(getClass(), name));
    Path path = target.toPath().resolve(new File(name).getName());
    Files.write(path, bytes);
    if (!path.toFile().setExecutable(true)) {
      throw new IOException("failed to make executable: " + path);
    }
  }
}

相关文章

微信公众号

最新文章

更多