下面列出了com.google.common.io.Files#touch ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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()));
}
@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);
}
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);
}
}
@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);
}
}
@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();
}
@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);
}
@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());
}
@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));
}
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;
}
@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);
}
@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)));
}
public static void saveFile(File f, byte[] content) throws IOException {
Files.touch(f);
try (FileOutputStream fileOuputStream = new FileOutputStream(f))
{
fileOuputStream.write(content);
}
}
@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);
}
}
@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());
}
private File touchCacheResourceVersionLockFile(final File resourceVersionDir) throws IOException {
final File lockFile = getCacheResourceVersionLockFile(resourceVersionDir);
Files.touch(lockFile);
return lockFile;
}
/**
* 创建文件或更新时间戳.
*/
public static void touch(String filePath) throws IOException {
Files.touch(getFileByPath(filePath));
}
@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());
}
}
private File touchTempDir(String prefix, FileSystem fs) throws IOException {
File out = fs.getTemporaryDirectory(prefix, lifetimes.currentTask());
Files.touch(out);
return out;
}
@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();
}
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();
}
}