com.google.common.io.Files#write ( )源码实例Demo

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

源代码1 项目: mt-flume   文件: TestSpoolingFileLineReader.java
@Test
// Test the case where we read finish reading and fully commit a file, then
//  the directory is empty.
public void testEmptyDirectoryAfterCommittingFile() throws IOException {
  File f1 = new File(tmpDir.getAbsolutePath() + "/file1");

  Files.write("file1line1\nfile1line2\n", f1, Charsets.UTF_8);

  ReliableSpoolingFileEventReader parser = getParser();

  List<String> allLines = bodiesAsStrings(parser.readEvents(2));
  assertEquals(2, allLines.size());
  parser.commit();

  List<String> empty = bodiesAsStrings(parser.readEvents(10));
  assertEquals(0, empty.size());
}
 
源代码2 项目: cdep   文件: TestBootstrap.java
public void testLocalFile() throws Exception {
    File localCDep = new File("./local-test-files/cdep-alpha-0.0.29.jar").getAbsoluteFile();
    File localSnake = new File("./local-test-files/snakeyaml-1.17.jar").getAbsoluteFile();
    if (!localCDep.exists()) {
         localCDep = new File("../../bootstrap/local-test-files/cdep-alpha-0.0.29.jar")
                 .getAbsoluteFile().getCanonicalFile();
         localSnake = new File("../../bootstrap/local-test-files/snakeyaml-1.17.jar")
                 .getAbsoluteFile().getCanonicalFile();
    }
    assertThat(localCDep.exists()).isTrue();
    assertThat(localSnake.exists()).isTrue();
    getDownloadFolder().mkdirs();
    File manifest = new File(getDownloadFolder().getParentFile().getParentFile(),
            "bootstrap.yml").getAbsoluteFile();
    StringBuilder sb = new StringBuilder();
    sb.append("entry: com.jomofisher.cdep.CDep\n");
    sb.append("dependencies:\n");
    sb.append(String.format("- %s\n", localCDep.toString()));
    sb.append(String.format("- %s\n", localSnake.toString()));
    Files.write(sb.toString(), manifest, StandardCharsets.UTF_8);
    String result = main(manifest.getAbsolutePath(), "--version");
    System.out.printf(result);
}
 
源代码3 项目: WebIDE-Backend   文件: KeyManagerImpl.java
@Override
public void copyToWorkspace(Workspace ws) {
    try {
        if (!isKeyExist()) generateKey();

        Key key = getKey();

        Files.write(key.getPublicKey(), getPublicKeyFile(ws), defaultCharset());
        Files.write(key.getPrivateKey(), getPrivateKeyFile(ws), defaultCharset());
        Files.write(format("coding.net %s\n", CODING_PUB_KEY), getKnownHostsFile(ws), defaultCharset());
        
        //ignore on windows.
        if (!IS_OS_WINDOWS) {
            //using PosixFilePermission to set file permissions 600
            setPosixFilePermissions(getPrivateKeyFile(ws).toPath(), newHashSet(OWNER_READ, OWNER_WRITE));
        }
    } catch (IOException e) {
        log.error("copy key to workspace failed", e);
    }
}
 
@Test
public void test_tooHigh() throws IOException {
    final String contents =
            "<hivemq>" +
                    "<restrictions>" +
                    "<max-connections>500</max-connections>" +
                    "<max-client-id-length>123456</max-client-id-length>" +
                    "<max-topic-length>123456</max-topic-length>" +
                    "<no-connect-idle-timeout>300</no-connect-idle-timeout>" +
                    "<incoming-bandwidth-throttling>200</incoming-bandwidth-throttling>" +
                    "</restrictions>" +
                    "</hivemq>";
    Files.write(contents.getBytes(UTF_8), xmlFile);

    reader.applyConfig();

    assertEquals(500, restrictionsConfigurationService.maxConnections());
    assertEquals(MAX_CLIENT_ID_LENGTH_DEFAULT, restrictionsConfigurationService.maxClientIdLength());
    assertEquals(MAX_TOPIC_LENGTH_DEFAULT, restrictionsConfigurationService.maxTopicLength());
    assertEquals(300, restrictionsConfigurationService.noConnectIdleTimeout());
    assertEquals(200, restrictionsConfigurationService.incomingLimit());
}
 
源代码5 项目: sarl   文件: MavenImportUtils.java
/** Force the pom file of a project to be "simple".
 *
 * @param projectDir the folder in which the pom file is located.
 * @param monitor the progress monitor.
 * @throws IOException if the pom file cannot be changed.
 */
static void forceSimplePom(File projectDir, IProgressMonitor monitor) throws IOException {
	final File pomFile = new File(projectDir, POM_FILE);
	if (pomFile.exists()) {
		final SubMonitor submon = SubMonitor.convert(monitor, 4);
		final File savedPomFile = new File(projectDir, POM_BACKUP_FILE);
		if (savedPomFile.exists()) {
			savedPomFile.delete();
		}
		submon.worked(1);
		Files.copy(pomFile, savedPomFile);
		submon.worked(1);
		final StringBuilder content = new StringBuilder();
		try (BufferedReader stream = new BufferedReader(new FileReader(pomFile))) {
			String line = stream.readLine();
			while (line != null) {
				line = line.replaceAll("<extensions>\\s*true\\s*</extensions>", ""); //$NON-NLS-1$ //$NON-NLS-2$
				content.append(line).append("\n"); //$NON-NLS-1$
				line = stream.readLine();
			}
		}
		submon.worked(1);
		Files.write(content.toString().getBytes(), pomFile);
		submon.worked(1);
	}
}
 
@Test
public void test_restrictions_xml() throws Exception {

    final String contents =
            "<hivemq>" +
                    "<restrictions>" +
                    "<max-connections>500</max-connections>" +
                    "<max-client-id-length>400</max-client-id-length>" +
                    "<max-topic-length>400</max-topic-length>" +
                    "<no-connect-idle-timeout>300</no-connect-idle-timeout>" +
                    "<incoming-bandwidth-throttling>200</incoming-bandwidth-throttling>" +
                    "</restrictions>" +
                    "</hivemq>";
    Files.write(contents.getBytes(UTF_8), xmlFile);

    reader.applyConfig();

    assertEquals(500, restrictionsConfigurationService.maxConnections());
    assertEquals(400, restrictionsConfigurationService.maxClientIdLength());
    assertEquals(400, restrictionsConfigurationService.maxTopicLength());
    assertEquals(300, restrictionsConfigurationService.noConnectIdleTimeout());
    assertEquals(200, restrictionsConfigurationService.incomingLimit());

}
 
源代码7 项目: cdep   文件: TestCDep.java
@Test
public void download() throws Exception {
  CDepYml config = new CDepYml();
  File yaml = new File(".test-files/download/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\n" +
          "dependencies:\n" +
          "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml,
      StandardCharsets.UTF_8);
  // Download first.
  main("-wf", yaml.getParent());
  // Redownload
  String result = main("download", "-wf", yaml.getParent());
  System.out.printf(result);
  assertThat(result).doesNotContain("Redownload");
  assertThat(result).contains("Generating");
}
 
源代码8 项目: cdep   文件: TestCDep.java
@Test
public void unfindableLocalFile() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/unfindableLocalFile/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: ../not-a-file/cdep-manifest.yml\n",
      yaml, StandardCharsets.UTF_8);

  try {
    main("-wf", yaml.getParent());
    fail("Expected failure");
  } catch (CDepRuntimeException e) {
    assertThat(e).hasMessage("Could not resolve '../not-a-file/cdep-manifest.yml'. It doesn't exist.");
    assertThat(e.errorInfo.file).endsWith("cdep.yml");
    assertThat(e.errorInfo.code).isEqualTo("c35a5b0");
  }
}
 
源代码9 项目: datacollector   文件: TestSFTPRemoteConnector.java
@Test
public void testStrictHostChecking() throws Exception {
  File knownHostsFile = testFolder.newFile("hosts");
  Files.write(getHostsFileEntry(), knownHostsFile);

  SFTPRemoteConnectorForTest connector = new SFTPRemoteConnectorForTest(getBean(
      "sftp://localhost:" + port + "/",
      true,
      false,
      TESTUSER,
      TESTPASS,
      null,
      null,
      knownHostsFile.toString(),
      false,
      null
  ));

  List<Stage.ConfigIssue> issues = initWithNoIssues(connector);
  Assert.assertEquals(0, issues.size());
  verifyConnection(connector);

  connector.close();
}
 
public static void main(String[] args)
    throws IOException, CertificateException, InvalidKeySpecException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException {
  if (args.length < 1) {
    System.out.println(
        String.format(
            "Usage: %s <certificates chain> [output file]",
            UploadCertificate.class.getSimpleName()));
    return;
  }

  String pemFile = args[0];

  List<Certificate> certs = CryptoDataLoader.certificatesFromFile(new File(pemFile));
  System.out.println(String.format("Total number of certificates in chain: %d", certs.size()));

  HttpLogClient client = new HttpLogClient("http://ct.googleapis.com/pilot/ct/v1/");

  Ct.SignedCertificateTimestamp resp = client.addCertificate(certs);

  System.out.println(resp);
  if (args.length >= 2) {
    String outputFile = args[1];
    //TODO(eranm): Binary encoding compatible with the C++ code.
    Files.write(resp.toByteArray(), new File(outputFile));
  }
}
 
源代码11 项目: datacollector   文件: TestJmsTarget.java
@Before
public void setUp() throws Exception {
  baseDir = Files.createTempDir();
  tmpDir = new File(baseDir, "tmp");
  dataDir = new File(baseDir, "data");
  Assert.assertTrue(tmpDir.mkdir());
  passwordFile = new File(baseDir, "password");
  Files.write(PASSWORD.getBytes(StandardCharsets.UTF_8), passwordFile);

  broker = new BrokerService();

  broker.addConnector(BROKER_BIND_URL);
  broker.setTmpDataDirectory(tmpDir);
  broker.setDataDirectoryFile(dataDir);
  List<AuthenticationUser> users = Lists.newArrayList();
  users.add(new AuthenticationUser(USERNAME, PASSWORD, ""));
  SimpleAuthenticationPlugin authentication = new SimpleAuthenticationPlugin(users);
  broker.setPlugins(new BrokerPlugin[]{authentication});
  broker.start();

  credentialsConfig = new CredentialsConfig();
  jmsTargetConfig = new JmsTargetConfig();
  credentialsConfig.useCredentials = true;
  credentialsConfig.username = () -> USERNAME;
  credentialsConfig.password = () -> PASSWORD;
  jmsTargetConfig.destinationName = JNDI_PREFIX + DESTINATION_NAME;
  jmsTargetConfig.initialContextFactory = INITIAL_CONTEXT_FACTORY;
  jmsTargetConfig.connectionFactory = CONNECTION_FACTORY;
  jmsTargetConfig.providerURL = BROKER_BIND_URL;
  // Create a connection and start
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  connection = factory.createConnection();
  connection.start();
}
 
源代码12 项目: datacollector   文件: TestRemoteUploadTarget.java
@Test
public void testFileExistsToError() throws Exception {
  FileRefTestUtil.writePredefinedTextToFile(testFolder.getRoot());
  Record record = createRecord();

  final String OTHER_TEXT = "some other text";
  File targetFile = testFolder.newFile("target.txt");
  Files.write(OTHER_TEXT.getBytes(Charset.forName("UTF-8")), targetFile);
  Assert.assertEquals(OTHER_TEXT, Files.readFirstLine(targetFile, Charset.forName("UTF-8")));

  path = testFolder.getRoot().getAbsolutePath();
  setupServer(path, true);

  RemoteUploadTarget target = new RemoteUploadTarget(getBean(
      scheme.name() + "://localhost:" + port + "/",
      true,
      DataFormat.WHOLE_FILE,
      targetFile.getName(),
      WholeFileExistsAction.TO_ERROR
  ));
  TargetRunner runner = new TargetRunner.Builder(RemoteUploadDTarget.class, target).build();
  runner.runInit();
  runner.runWrite(Collections.singletonList(record));

  List<Record> errorRecords = runner.getErrorRecords();
  Assert.assertEquals(1, errorRecords.size());
  Assert.assertEquals(Errors.REMOTE_UPLOAD_02.getCode(), errorRecords.get(0).getHeader().getErrorCode());
  Assert.assertEquals(record.get().getValueAsMap(), errorRecords.get(0).get().getValueAsMap());

  Assert.assertEquals(0, runner.getEventRecords().size());

  String line = Files.readFirstLine(targetFile, Charset.forName("UTF-8"));
  Assert.assertEquals(OTHER_TEXT, line);

  destroyAndValidate(runner);
}
 
源代码13 项目: camunda-bpm-elasticsearch   文件: IoUtil.java
public static void writeToFile(byte[] content, String fileName, boolean createFile) {
  File file = new File(fileName);
  try {
    if (createFile) {
      Files.createParentDirs(file);
      file.createNewFile();
    }

    Files.write(content, file);
  } catch (IOException e) {
    // nop
  }
}
 
源代码14 项目: datacollector   文件: TestSFTPStreamFactory.java
@Before
public void setUp() throws Exception {
  File file = testFolder.newFile("file.txt");
  String text = "hello";
  Files.write(text.getBytes(Charset.forName("UTF-8")), file);
  Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));

  path = testFolder.getRoot().getAbsolutePath();
  setupSSHD(path);
  SSHClient sshClient = createSSHClient();

  SFTPClient sftpClient = sshClient.newSFTPClient();
  remoteFile = sftpClient.open(file.getName(), EnumSet.of(OpenMode.READ));
  remoteFile = Mockito.spy(remoteFile);
}
 
源代码15 项目: emodb   文件: FileScanWriter.java
@Override
protected boolean writeScanCompleteFile(URI fileUri, byte[] contents)
        throws IOException {
    File file = new File(fileUri.toURL().getFile());
    if (file.exists()) {
        // Complete already marked; take no action
        return false;

    }
    Files.createParentDirs(file);
    Files.write(contents, file);
    return true;
}
 
源代码16 项目: brooklyn-server   文件: MiscClassesRebindTest.java
protected Entity loadEntityMemento(String label, String entityId) throws Exception {
    String mementoResourceName = JavaClassNames.cleanSimpleClassName(this) + "-" + label + "-entity-" + entityId+".memento";
    String memento = Streams.readFullyString(getClass().getResourceAsStream(mementoResourceName));
    
    File persistedEntityFile = new File(mementoDir, Os.mergePaths("entities", entityId));
    Files.write(memento.getBytes(), persistedEntityFile);
    
    return newApp = rebind();
}
 
源代码17 项目: blueocean-plugin   文件: ATHJUnitRunner.java
private void writeScreenShotCause(Throwable t, Object test, FrameworkMethod method) throws IOException {
    WebDriver driver = injector.getInstance(WebDriver.class);
    File file = new File("target/screenshots/"+ test.getClass().getName() + "_" + method.getName() + ".png");

    Throwable cause = t.getCause();
    boolean fromException = false;
    while(cause != null) {
        if(cause instanceof ScreenshotException) {
            ScreenshotException se = ((ScreenshotException) cause);

            byte[] screenshot =  Base64.getMimeDecoder().decode(se.getBase64EncodedScreenshot());

            Files.createParentDirs(file);
            Files.write(screenshot, file);
            logger.info("Wrote screenshot to " + file.getAbsolutePath());
            fromException = true;
            break;
        } else {
            cause = cause.getCause();
        }
    }

    if(!fromException) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, file);
        logger.info("Wrote screenshot to " + file.getAbsolutePath());
    }
}
 
源代码18 项目: datamill   文件: CommandLineSteps.java
public void doCreateFile(String file, String content) throws IOException {
    File temporaryDirectory = getOrCreateTemporaryDirectory();

    String resolvedFile = placeholderResolver.resolve(file);

    File fileWithinDirectory = new File(temporaryDirectory, resolvedFile);
    Files.write(content, fileWithinDirectory, Charset.defaultCharset());
}
 
源代码19 项目: brooklyn-server   文件: ItemLister.java
private void copyFromItemListerClasspathBaseStaticsToOutputDir(ResourceUtils resourceUtils, String item, String dest) throws IOException {
    String js = resourceUtils.getResourceAsString(Urls.mergePaths(BASE_STATICS, item));
    Files.write(js, new File(Os.mergePaths(outputFolder, dest)), Charsets.UTF_8);
}
 
源代码20 项目: appinventor-extensions   文件: TempFiles.java
/**
 * Creates a temporary file for the given data.
 *
 * @param data  data to write into the temporary file
 * @return  file descriptor for temporary file
 * @throws IOException
 */
public static File createTempFile(byte[] data) throws IOException {
  File tmpFile = File.createTempFile("ode", null, tempRoot);
  Files.write(data, tmpFile);
  return tmpFile;
}