Java Code Examples for com.google.common.io.Files#touch()

The following examples show how to use com.google.common.io.Files#touch() . 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: MainTest.java    From thompson-sampling with Apache License 2.0 6 votes vote down vote up
private void banditTest(List<Double> armWeights, BanditCreator creator, String name) throws IOException {
  File file = new File(format("/tmp/bandit-results/%s.csv", name));
  Files.createParentDirs(file);
  Files.touch(file);
  List<BernouliArm> arms = FluentIterable.from(armWeights).transform(new Function<Double, BernouliArm>() {
    @Override
    public BernouliArm apply(Double aDouble) {
      return new BernouliArm(aDouble, engine);
    }
  }).toList();
  for (int i = 0; i < 10000; i++) {
    BatchedBanditTester tester = new BatchedBanditTester(creator.bandit(), engine, arms);
    String l = format("%d,%d,%f\n", tester.getWinningArm(), tester.getIterations(), tester.getCumulativeRegret());
    Files.append(l, file, Charsets.UTF_8);
  }
}
 
Example 2
Source File: TestProdTypePatternMetExtractor.java    From oodt with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    URL url = getClass().getResource("/product-type-patterns.xml");
    configFile = new File(url.toURI());
    extractor = new ProdTypePatternMetExtractor();
    extractor.setConfigFile(configFile);

    tmpDir = Files.createTempDir();
    book1 = new File(tmpDir, "book-1234567890.txt");
    book2 = new File(tmpDir, "book-0987654321.txt");
    page1 = new File(tmpDir, "page-1234567890-111.txt");
    page2 = new File(tmpDir, "page-0987654321-222.txt");
    Files.touch(book1);
    Files.touch(book2);
    Files.touch(page1);
    Files.touch(page2);

    url = getClass().getResource("/product-type-patterns-2.xml");
    configFile2 = new File(url.toURI());
    page1a = new File(tmpDir, "page-111-1234567890.txt");
    page2a = new File(tmpDir, "page-222-0987654321.txt");
    Files.touch(page1a);
    Files.touch(page2a);
}
 
Example 3
Source File: ChangeFileLastModifiedDate.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Files.touch creates an empty file or updates the last updated timestamp
 * on the same as the unix command of the same name.
 * 
 * @throws IOException
 */
@Test
public void touch_file_guava() throws IOException {

	SimpleDateFormat dateFormatter = new SimpleDateFormat(
			"MM/dd/yyyy HH:mm:ss");
	DateTime today = new DateTime();

	File file = new File(OUTPUT_FILE_NAME);

	// set last modified to 5 days ago
	file.setLastModified(today.minusDays(5).getMillis());

	// display latest lastmodified
	logger.info(dateFormatter.format(file.lastModified()));

	Files.touch(file);

	// display latest lastmodified
	logger.info(dateFormatter.format(file.lastModified()));
}
 
Example 4
Source File: FileProcessorImpl.java    From accelerator-initializer with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public File touch(Path path) {
    try {
        File file = path.toFile();
        Files.touch(file);
        return file;
    } catch (IOException e) {
        log.error("It was not possible create file {}", path);
        throw new InitializerException("It was not possible to create file", e);
    }
}
 
Example 5
Source File: IndividualFilesPersistenceHandler.java    From AuthMeReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveLimboPlayer(Player player, LimboPlayer limboPlayer) {
    String id = player.getUniqueId().toString();
    try {
        File file = new File(cacheDir, id + File.separator + "data.json");
        Files.createParentDirs(file);
        Files.touch(file);
        Files.write(gson.toJson(limboPlayer), file, StandardCharsets.UTF_8);
    } catch (IOException e) {
        logger.logException("Failed to write " + player.getName() + " data:", e);
    }
}
 
Example 6
Source File: FileTools.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public static void saveFile(File f, byte[] content) throws IOException {
	
	Files.touch(f);
	
	 try (FileOutputStream fileOuputStream = new FileOutputStream(f)) 
	 {
            fileOuputStream.write(content);
	 } 
}
 
Example 7
Source File: TestSpoolingFileLineReader.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@Test
public void testBehaviorWithEmptyFile() throws IOException {
  File f1 = new File(tmpDir.getAbsolutePath() + "/file0");
  Files.touch(f1);

  ReliableSpoolingFileEventReader parser = getParser();

  File f2 = new File(tmpDir.getAbsolutePath() + "/file1");
  Files.write("file1line1\nfile1line2\nfile1line3\nfile1line4\n" +
              "file1line5\nfile1line6\nfile1line7\nfile1line8\n",
              f2, Charsets.UTF_8);

  // Expect to skip over first file
  List<String> out = bodiesAsStrings(parser.readEvents(8));

  parser.commit();
  assertEquals(8, out.size());

  assertTrue(out.contains("file1line1"));
  assertTrue(out.contains("file1line2"));
  assertTrue(out.contains("file1line3"));
  assertTrue(out.contains("file1line4"));
  assertTrue(out.contains("file1line5"));
  assertTrue(out.contains("file1line6"));
  assertTrue(out.contains("file1line7"));
  assertTrue(out.contains("file1line8"));

  assertNull(parser.readEvent());

  // Make sure original is deleted
  List<File> outFiles = Lists.newArrayList(tmpDir.listFiles(directoryFilter()));
  assertEquals(2, outFiles.size());
  assertTrue("Outfiles should have file0 & file1: " + outFiles,
      outFiles.contains(new File(tmpDir + "/file0" + completedSuffix)));
  assertTrue("Outfiles should have file0 & file1: " + outFiles,
      outFiles.contains(new File(tmpDir + "/file1" + completedSuffix)));
}
 
Example 8
Source File: AccountsUtilsTest.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Test
public void getUnclaimedExperimentCount() throws Exception {
  // Create files representing 5 unclaimed experiments.
  File unclaimedExperimentsDir = new File(context.getFilesDir(), "experiments");
  for (int i = 1; i <= 5; i++) {
    String experimentId = "experiment_id_" + i;
    File experimentDir = new File(unclaimedExperimentsDir, experimentId);
    experimentDir.mkdirs();
    Files.touch(new File(experimentDir, "experiment.proto"));
  }

  assertThat(AccountsUtils.getUnclaimedExperimentCount(context)).isEqualTo(5);
}
 
Example 9
Source File: FileComparatorTest.java    From kafka-connect-spooldir with Apache License 2.0 5 votes vote down vote up
File createFile(String name, long date, long length) throws IOException {
  File result = new File(tempDirectory, name);

  if (length == 0) {
    Files.touch(result);
  } else {
    Files.write(
        new byte[(int) length],
        result
    );
  }
  result.setLastModified(date);
  return result;
}
 
Example 10
Source File: ProcessingFileExistsPredicateTest.java    From kafka-connect-spooldir with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws IOException {
  File processingFlag = InputFileDequeue.processingFile(EXTENSION, this.inputFile);
  Files.touch(processingFlag);
  assertFalse(this.predicate.test(this.inputFile));
  processingFlag.delete();
  assertTrue(this.predicate.test(this.inputFile));
}
 
Example 11
Source File: CreateFilesUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCreatingAFileWithFileSeparator_thenFileIsCreated() throws IOException {
    File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
    File newFile = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile2.txt");

    assertFalse(newFile.exists());

    Files.touch(newFile);

    assertTrue(newFile.exists());
}
 
Example 12
Source File: FilesUtils.java    From reposilite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "UnstableApiUsage", "deprecation" })
public static void writeFileChecksums(Path path) throws IOException {
    Files.touch(new File(path + ".md5"));
    Files.touch(new File(path + ".sha1"));

    Path md5FileFile = Paths.get(path + ".md5");
    Path sha1FileFile = Paths.get(path + ".sha1");

    FileUtils.writeStringToFile(md5FileFile.toFile(), Files.hash(md5FileFile.toFile(), Hashing.md5()).toString(), StandardCharsets.UTF_8);
    FileUtils.writeStringToFile(sha1FileFile.toFile(), Files.hash(sha1FileFile.toFile(), Hashing.sha1()).toString(), StandardCharsets.UTF_8);
}
 
Example 13
Source File: FileOutputDiffListener.java    From circus-train with Apache License 2.0 5 votes vote down vote up
@Override
public void onDiffStart(TableAndMetadata source, Optional<TableAndMetadata> replica) {
  try {
    Files.touch(file);
    out = new PrintStream(file, StandardCharsets.UTF_8.name());
  } catch (IOException e) {
    throw new CircusTrainException(e.getMessage(), e);
  }
  out.println("=================================================================================================");
  out.printf("Starting diff on source table 'table=%s, location=%s' and replicate table 'table=%s, location=%s'",
      source.getSourceTable(), source.getSourceLocation(),
      replica.isPresent() ? replica.get().getSourceTable() : "null",
      replica.isPresent() ? replica.get().getSourceLocation() : "null");
  out.println();
}
 
Example 14
Source File: FileUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 创建文件或更新时间戳.
 */
public static void touch(String filePath) throws IOException {
	Files.touch(getFileByPath(filePath));
}
 
Example 15
Source File: FetchingCacheServiceImpl.java    From genie with Apache License 2.0 4 votes vote down vote up
private File touchCacheResourceVersionLockFile(final File resourceVersionDir) throws IOException {
    final File lockFile = getCacheResourceVersionLockFile(resourceVersionDir);
    Files.touch(lockFile);
    return lockFile;
}
 
Example 16
Source File: TestChrootSFTPClient.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testLs() throws Exception {
  File fileInRoot = testFolder.newFile("fileInRoot.txt");
  File dirInRoot = testFolder.newFolder("dirInRoot");
  File fileInDirInRoot = new File(dirInRoot, "fileInDirInRoot.txt");
  Files.touch(fileInDirInRoot);

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

  /**
   * ...
   * ├── path (root)
   * │   ├─── fileInRoot.txt
   * │   ├─── dirInRoot
   * │   │    └── fileInDirInRoot.txt
   */

  for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) {
    List<ChrootSFTPClient.SimplifiedRemoteResourceInfo> files = sftpClient.ls();
    Assert.assertEquals(2, files.size());
    for (ChrootSFTPClient.SimplifiedRemoteResourceInfo file : files) {
      if (file.getType() == FileMode.Type.REGULAR) {
        Assert.assertEquals("/" + fileInRoot.getName(), file.getPath());
      } else {  // dir
        Assert.assertEquals("/" + dirInRoot.getName(), file.getPath());
      }
    }
    // We can specify a dir as either a relative path "dirInRoot" or an absolute path "/dirInRoot" and they should be
    // equivalent
    for (String p : new String[] {
        dirInRoot.getName(),
        "/" + dirInRoot.getName(),
    })
    files = sftpClient.ls(p);
    Assert.assertEquals(1, files.size());
    Assert.assertEquals("/" + dirInRoot.getName() + "/" + fileInDirInRoot.getName(),
        files.iterator().next().getPath());
  }
}
 
Example 17
Source File: SystemFileSystemTest.java    From MOE with Apache License 2.0 4 votes vote down vote up
private File touchTempDir(String prefix, FileSystem fs) throws IOException {
  File out = fs.getTemporaryDirectory(prefix, lifetimes.currentTask());
  Files.touch(out);
  return out;
}
 
Example 18
Source File: SystemFileSystemTest.java    From MOE with Apache License 2.0 4 votes vote down vote up
@Test
public void testCleanUpTempDirsWithTasks() throws Exception {
  DaggerSystemFileSystemTest_Component.create().inject(this);

  File taskless = fs.getTemporaryDirectory("taskless", lifetimes.moeExecution());
  Files.touch(taskless);

  File innerPersist;
  File outer1;
  File outer2;
  try (Task outer = ui.newTask("outer", "outer")) {
    outer1 = touchTempDir("outer1", fs);
    outer2 = touchTempDir("outer2", fs);

    File inner1;
    File inner2;
    try (Task inner = ui.newTask("inner", "inner")) {
      inner1 = touchTempDir("inner1", fs);
      inner2 = touchTempDir("inner2", fs);
      innerPersist = fs.getTemporaryDirectory("innerPersist", lifetimes.moeExecution());
      Files.touch(innerPersist);

      inner.result().append("popping inner, persisting nothing");
    }
    assertThat(inner1.exists()).named("inner1").isFalse();
    assertThat(inner2.exists()).named("inner2").isFalse();
    assertThat(innerPersist.exists()).named("innerPersist").isTrue();
    assertThat(taskless.exists()).named("taskless").isTrue();
    assertThat(outer1.exists()).named("outer1").isTrue();
    assertThat(outer2.exists()).named("outer2").isTrue();

    outer.result().append("popping outer, persisting nothing");
  }
  assertThat(outer1.exists()).named("outer1").isFalse();
  assertThat(outer2.exists()).named("outer2").isFalse();
  assertThat(innerPersist.exists()).named("innerPersist").isTrue();
  assertThat(taskless.exists()).named("taskless").isTrue();

  try (Task moeTermination = ui.newTask(Ui.MOE_TERMINATION_TASK_NAME, "Final clean-up")) {
    fs.cleanUpTempDirs();
    moeTermination.result().append("Finished clean-up");
  }
  assertThat(innerPersist.exists()).named("innerPersist").isFalse();
  assertThat(taskless.exists()).named("taskless").isFalse();
}
 
Example 19
Source File: LocalPersistenceFileUtilTest.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@Test
public void test_dont_overwrite_if_folder_already_exists() throws Exception {

    final File dataFolder = temporaryFolder.newFolder();
    final File persistenceFolder = new File(dataFolder, "persistence");
    assertTrue(persistenceFolder.mkdir());

    final File tempFile = new File(persistenceFolder, "testfile.tmp");
    Files.touch(tempFile);

    final SystemInformation systemInfoForTest = createInfoForTest(dataFolder);
    final LocalPersistenceFileUtil util = new LocalPersistenceFileUtil(systemInfoForTest);


    util.getLocalPersistenceFolder();

    //File wasn't overwritten
    assertEquals(true, tempFile.exists());
}
 
Example 20
Source File: Tools.java    From torrenttunes-client with GNU General Public License v3.0 3 votes vote down vote up
public static void addExternalWebServiceVarToTools() {

		log.info("tools.js = " + DataSources.TOOLS_JS());
		try {
			List<String> lines = java.nio.file.Files.readAllLines(Paths.get(DataSources.TOOLS_JS()));

			String interalServiceLine = "var localSparkService = '" + 
					DataSources.WEB_SERVICE_URL + "';";

			String torrentTunesServiceLine = "var torrentTunesSparkService ='" + 
					DataSources.TORRENTTUNES_URL + "';";

			String externalServiceLine = "var externalSparkService ='" + 
					DataSources.EXTERNAL_URL + "';";

			lines.set(0, interalServiceLine);
			lines.set(1, torrentTunesServiceLine);
			lines.set(2, externalServiceLine);


			java.nio.file.Files.write(Paths.get(DataSources.TOOLS_JS()), lines);
			Files.touch(new File(DataSources.TOOLS_JS()));


		} catch (IOException e) {
			e.printStackTrace();
		}

	}