List of usage examples for java.nio.file Files setLastModifiedTime
public static Path setLastModifiedTime(Path path, FileTime time) throws IOException
From source file:Main.java
public static void main(String[] args) throws Exception { long time = System.currentTimeMillis(); FileTime fileTime = FileTime.fromMillis(time); Path path = Paths.get("C:/tutorial/Java/JavaFX", "Topic.txt"); try {//ww w . java 2 s.c om Files.setLastModifiedTime(path, fileTime); } catch (IOException e) { System.err.println(e); } }
From source file:com.netflix.nicobar.core.persistence.ArchiveRepositoryTest.java
/** * Test insert, update, delete//from w w w . ja v a 2 s . com */ @Test public void testRoundTrip() throws Exception { ArchiveRepository repository = createRepository(); JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); ModuleId testModuleId = TEST_MODULE_SPEC_JAR.getModuleId(); repository.insertArchive(jarScriptArchive); Map<ModuleId, Long> archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); long expectedUpdateTime = Files.getLastModifiedTime(testArchiveJarFile).toMillis(); assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime)); // assert getScriptArchives Set<ScriptArchive> scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet()); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); ScriptArchive scriptArchive = scriptArchives.iterator().next(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId); assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime); // assert getArchiveSummaries List<ArchiveSummary> archiveSummaries = repository.getDefaultView().getArchiveSummaries(); assertEquals(archiveSummaries.size(), 1); ArchiveSummary archiveSummary = archiveSummaries.get(0); assertEquals(archiveSummary.getModuleId(), testModuleId); assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime); // assert getRepositorySummary RepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary(); assertNotNull(repositorySummary); assertEquals(repositorySummary.getArchiveCount(), 1); assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime); // advance the timestamp by 10 seconds and update expectedUpdateTime = expectedUpdateTime + 10000; Files.setLastModifiedTime(testArchiveJarFile, FileTime.fromMillis(expectedUpdateTime)); jarScriptArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); repository.insertArchive(jarScriptArchive); archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); assertEquals(archiveUpdateTimes, Collections.singletonMap(testModuleId, expectedUpdateTime)); // assert getScriptArchives scriptArchives = repository.getScriptArchives(archiveUpdateTimes.keySet()); assertEquals(scriptArchives.size(), 1, scriptArchives.toString()); scriptArchive = scriptArchives.iterator().next(); assertEquals(scriptArchive.getModuleSpec().getModuleId(), testModuleId); assertEquals(scriptArchive.getCreateTime(), expectedUpdateTime); // assert getArchiveSummaries archiveSummaries = repository.getDefaultView().getArchiveSummaries(); assertEquals(archiveSummaries.size(), 1); archiveSummary = archiveSummaries.get(0); assertEquals(archiveSummary.getModuleId(), testModuleId); assertEquals(archiveSummary.getLastUpdateTime(), expectedUpdateTime); // assert getRepositorySummary repositorySummary = repository.getDefaultView().getRepositorySummary(); assertNotNull(repositorySummary); assertEquals(repositorySummary.getArchiveCount(), 1); assertEquals(repositorySummary.getLastUpdated(), expectedUpdateTime); // delete module repository.deleteArchive(testModuleId); archiveUpdateTimes = repository.getDefaultView().getArchiveUpdateTimes(); assertTrue(archiveUpdateTimes.isEmpty(), archiveUpdateTimes.toString()); }
From source file:com.github.wellcomer.query3.core.Autocomplete.java
/** ?. ?, TreeSet ? ? ?. ? TreeSet . //from ww w. ja va 2 s.c om @param queryList ?? ?. @param scanModifiedOnly ? ?. @param mergePrevious ?? ? ?? . */ public void autolearn(QueryList queryList, boolean scanModifiedOnly, boolean mergePrevious) throws IOException { FileTime timestamp; long modifiedSince = 0; Path timestampFilePath = Paths.get(filePath, ".timestamp"); if (scanModifiedOnly) { // try { // ? ? ? timestamp = Files.getLastModifiedTime(timestampFilePath); modifiedSince = timestamp.toMillis(); } catch (IOException e) { // ? ? Files.createFile(timestampFilePath); } } HashMap<String, TreeSet<String>> fields = new HashMap<>(); // - ? ?, - ? Iterator<Query> queryIterator = queryList.iterator(modifiedSince); // ? ?? ? ? ? String k, v; while (queryIterator.hasNext()) { Query query = queryIterator.next(); for (Map.Entry<String, String> entry : query.entrySet()) { k = entry.getKey().toLowerCase(); v = entry.getValue().trim(); if (v.length() < 2) continue; if (!fields.containsKey(k)) { TreeSet<String> treeSet = new TreeSet<>(); try { if (mergePrevious) { // ? ? List<String> lines = Files.readAllLines(Paths.get(filePath, k), charset); treeSet.addAll(lines); } } catch (IOException e) { e.printStackTrace(); } fields.put(k, treeSet); } TreeSet<String> treeSet = fields.get(k); treeSet.add(v); } } for (Map.Entry<String, TreeSet<String>> entry : fields.entrySet()) { k = entry.getKey(); ArrayList<String> lines = new ArrayList<>(fields.get(k)); FileWriter fileWriter = new FileWriter(Paths.get(filePath, k).toString()); fileWriter.write(StringUtils.join(lines, System.getProperty("line.separator"))); fileWriter.flush(); fileWriter.close(); } try { Files.setLastModifiedTime(timestampFilePath, FileTime.fromMillis(System.currentTimeMillis())); } catch (IOException e) { if (e.getClass().getSimpleName().equals("NoSuchFileException")) Files.createFile(timestampFilePath); e.printStackTrace(); } }
From source file:com.ethlo.geodata.util.ResourceUtil.java
private Entry<Date, File> downloadIfNewer(DataType dataType, Resource resource, CheckedFunction<Path, Path> fun) throws IOException { publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 0, 1)); final String alias = dataType.name().toLowerCase(); final File tmpDownloadedFile = new File(tmpDir, alias); final Date remoteLastModified = new Date(resource.lastModified()); final long localLastModified = tmpDownloadedFile.exists() ? tmpDownloadedFile.lastModified() : -2; logger.info(/*from ww w. ja v a 2 s .co m*/ "Local file for alias {}" + "\nPath: {}" + "\nExists: {}" + "\nLocal last-modified: {} " + "\nRemote last modified: {}", alias, tmpDownloadedFile.getAbsolutePath(), tmpDownloadedFile.exists(), formatDate(localLastModified), formatDate(remoteLastModified.getTime())); if (!tmpDownloadedFile.exists() || remoteLastModified.getTime() > localLastModified) { logger.info("Downloading {}", resource.getURL()); Files.copy(resource.getInputStream(), tmpDownloadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); logger.info("Download complete"); } final Path preppedFile = fun.apply(tmpDownloadedFile.toPath()); Files.setLastModifiedTime(tmpDownloadedFile.toPath(), FileTime.fromMillis(remoteLastModified.getTime())); Files.setLastModifiedTime(preppedFile, FileTime.fromMillis(remoteLastModified.getTime())); publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 1, 1)); return new AbstractMap.SimpleEntry<>(new Date(remoteLastModified.getTime()), preppedFile.toFile()); }
From source file:org.apache.taverna.robundle.manifest.TestManifestJSON.java
@Test public void createBundle() throws Exception { // Create bundle as in Example 3 of the specification // http://wf4ever.github.io/ro/bundle/2013-05-21/ try (Bundle bundle = Bundles.createBundle()) { Calendar createdOnCal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ENGLISH); // "2013-03-05T17:29:03Z" // Remember months are 0-based in java.util.Calendar! createdOnCal.set(2013, 3 - 1, 5, 17, 29, 03); createdOnCal.set(Calendar.MILLISECOND, 0); FileTime createdOn = FileTime.fromMillis(createdOnCal.getTimeInMillis()); Manifest manifest = bundle.getManifest(); manifest.setCreatedOn(createdOn); Agent createdBy = new Agent("Alice W. Land"); createdBy.setUri(URI.create("http://example.com/foaf#alice")); createdBy.setOrcid(URI.create("http://orcid.org/0000-0002-1825-0097")); manifest.setCreatedBy(createdBy); Path evolutionPath = bundle.getPath(".ro/evolution.ttl"); Files.createDirectories(evolutionPath.getParent()); Bundles.setStringValue(evolutionPath, "<manifest.json> < http://purl.org/pav/retrievedFrom> " + "<http://wf4ever.github.io/ro/bundle/2013-05-21/example/.ro/manifest.json> ."); manifest.getHistory().add(evolutionPath); Path jpeg = bundle.getPath("folder/soup.jpeg"); Files.createDirectory(jpeg.getParent()); Files.createFile(jpeg);/* w ww .j a va 2s. c o m*/ // register in manifest first bundle.getManifest().getAggregation(jpeg); URI blog = URI.create("http://example.com/blog/"); bundle.getManifest().getAggregation(blog); Path readme = bundle.getPath("README.txt"); Files.createFile(readme); PathMetadata readmeMeta = bundle.getManifest().getAggregation(readme); readmeMeta.setMediatype("text/plain"); Agent readmeCreatedby = new Agent("Bob Builder"); readmeCreatedby.setUri(URI.create("http://example.com/foaf#bob")); readmeMeta.setCreatedBy(readmeCreatedby); // 2013-02-12T19:37:32.939Z createdOnCal.set(2013, 2 - 1, 12, 19, 37, 32); createdOnCal.set(Calendar.MILLISECOND, 939); createdOn = FileTime.fromMillis(createdOnCal.getTimeInMillis()); Files.setLastModifiedTime(readme, createdOn); readmeMeta.setCreatedOn(createdOn); PathMetadata comments = bundle.getManifest() .getAggregation(URI.create("http://example.com/comments.txt")); comments.getOrCreateBundledAs().setURI(URI.create("urn:uuid:a0cf8616-bee4-4a71-b21e-c60e6499a644")); comments.getOrCreateBundledAs().setFolder(bundle.getPath("/folder/")); comments.getOrCreateBundledAs().setFilename("external.txt"); PathAnnotation jpegAnn = new PathAnnotation(); jpegAnn.setAbout(jpeg); Path soupProps = Bundles.getAnnotations(bundle).resolve("soup-properties.ttl"); Bundles.setStringValue(soupProps, "</folder/soup.jpeg> <http://xmlns.com/foaf/0.1/depicts> " + "<http://example.com/menu/tomato-soup> ."); jpegAnn.setContent(soupProps); // jpegAnn.setContent(URI.create("annotations/soup-properties.ttl")); jpegAnn.setUri(URI.create("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf")); manifest.getAnnotations().add(jpegAnn); PathAnnotation proxyAnn = new PathAnnotation(); proxyAnn.setAbout(comments.getBundledAs().getURI()); proxyAnn.setContent(URI.create("http://example.com/blog/they-aggregated-our-file")); manifest.getAnnotations().add(proxyAnn); Path metaAnn = Bundles.getAnnotations(bundle).resolve("a-meta-annotation-in-this-ro.txt"); Bundles.setStringValue(metaAnn, "This bundle contains an annotation about /folder/soup.jpeg"); PathAnnotation metaAnnotation = new PathAnnotation(); metaAnnotation.setAbout(bundle.getRoot()); metaAnnotation.getAboutList().add(URI.create("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf")); metaAnnotation.setContent(metaAnn); manifest.getAnnotations().add(metaAnnotation); Path jsonPath = bundle.getManifest().writeAsJsonLD(); ObjectMapper objectMapper = new ObjectMapper(); String jsonStr = Bundles.getStringValue(jsonPath); //System.out.println(jsonStr); JsonNode json = objectMapper.readTree(jsonStr); checkManifestJson(json); } }
From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java
/** * Creates a thumbnail for the image file using libvips * * @param file the image file/*from w w w.jav a 2 s .c o m*/ * @param thumbFile the resulting thumbnail file * @param size the size of the thumbnail */ private void createThumbnailUsingVips(Path file, Path thumbFile, IconSize size) throws IOException { try { // Example command: vipsthumbnail -s 64 -p bilinear -o thumb.png image2.jpg final Process proc = new ProcessBuilder(vipsCmd, "-s", String.valueOf(size.getSize()), "-p", "bilinear", "-o", thumbFile.toString(), file.toString()).directory(new File(System.getProperty("user.dir"))) .inheritIO().start(); BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug(line); } //Wait to get exit value int exitValue = proc.waitFor(); log.debug("Exit Value is " + exitValue); // Update the timestamp of the thumbnail file to match the change date of the image file Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file)); } catch (IOException | InterruptedException e) { log.error("Error creating thumbnail for image " + file, e); throw new IOException(e); } }
From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java
@Override public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException { Objects.requireNonNull(jarScriptArchive, "jarScriptArchive"); ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec(); ModuleId moduleId = moduleSpec.getModuleId(); Path moduleDir = rootDir.resolve(moduleId.toString()); if (Files.exists(moduleDir)) { FileUtils.deleteDirectory(moduleDir.toFile()); }// ww w. j ava2 s .co m JarFile jarFile; try { jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath()); } catch (URISyntaxException e) { throw new IOException(e); } try { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); Path entryName = moduleDir.resolve(jarEntry.getName()); if (jarEntry.isDirectory()) { Files.createDirectories(entryName); } else { InputStream inputStream = jarFile.getInputStream(jarEntry); try { Files.copy(inputStream, entryName); } finally { IOUtils.closeQuietly(inputStream); } } } } finally { IOUtils.closeQuietly(jarFile); } // write the module spec String serialized = moduleSpecSerializer.serialize(moduleSpec); Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()), serialized.getBytes(Charsets.UTF_8)); // update the timestamp on the module directory to indicate that the module has been updated Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime())); }
From source file:com.netflix.nicobar.core.persistence.JarArchiveRepository.java
@Override public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException { Objects.requireNonNull(jarScriptArchive, "jarScriptArchive"); ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec(); ModuleId moduleId = moduleSpec.getModuleId(); Path moduleJarPath = getModuleJarPath(moduleId); Files.deleteIfExists(moduleJarPath); JarFile sourceJarFile;/* w w w . ja v a 2s. c om*/ try { sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath()); } catch (URISyntaxException e) { throw new IOException(e); } JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile())); try { String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName(); Enumeration<JarEntry> sourceEntries = sourceJarFile.entries(); while (sourceEntries.hasMoreElements()) { JarEntry sourceEntry = sourceEntries.nextElement(); if (sourceEntry.getName().equals(moduleSpecFileName)) { // avoid double entry for module spec continue; } destJarFile.putNextEntry(sourceEntry); if (!sourceEntry.isDirectory()) { InputStream inputStream = sourceJarFile.getInputStream(sourceEntry); IOUtils.copy(inputStream, destJarFile); IOUtils.closeQuietly(inputStream); } destJarFile.closeEntry(); } // write the module spec String serialized = moduleSpecSerializer.serialize(moduleSpec); JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName()); destJarFile.putNextEntry(moduleSpecEntry); IOUtils.write(serialized, destJarFile); destJarFile.closeEntry(); } finally { IOUtils.closeQuietly(sourceJarFile); IOUtils.closeQuietly(destJarFile); } // update the timestamp on the jar file to indicate that the module has been updated Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime())); }
From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java
/** * Creates a thumbnail for the image file using plain old java * @param file the image file//from w w w .j a v a 2s.c om * @param thumbFile the resulting thumbnail file * @param size the size of the thumbnail */ private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException { try { BufferedImage image = ImageIO.read(file.toFile()); int w = image.getWidth(); int h = image.getHeight(); // Never scale up if (w <= size.getSize() && h <= size.getSize()) { FileUtils.copyFile(file.toFile(), thumbFile.toFile()); } else { // Compute the scale factor double dx = (double) size.getSize() / (double) w; double dy = (double) size.getSize() / (double) h; double d = Math.min(dx, dy); // Create the thumbnail BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = thumbImage.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(d, d); g2d.drawRenderedImage(image, at); g2d.dispose(); // Save the thumbnail String fileName = thumbFile.getFileName().toString(); ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile()); // Releas resources image.flush(); thumbImage.flush(); } // Update the timestamp of the thumbnail file to match the change date of the image file Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file)); } catch (Exception e) { log.error("Error creating thumbnail for image " + file, e); throw new IOException(e); } }
From source file:com.qwazr.library.archiver.ArchiverTool.java
public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException { try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) { try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) { ArchiveEntry entry;//from w w w . j a va 2 s . co m while ((entry = in.getNextEntry()) != null) { if (!in.canReadEntryData(entry)) continue; if (entry.isDirectory()) { final Path newDir = destDir.resolve(entry.getName()); if (!Files.exists(newDir)) Files.createDirectory(newDir); continue; } if (entry instanceof ZipArchiveEntry) if (((ZipArchiveEntry) entry).isUnixSymlink()) continue; final Path destFile = destDir.resolve(entry.getName()); final Path parentDir = destFile.getParent(); if (!Files.exists(parentDir)) Files.createDirectories(parentDir); final long entryLastModified = entry.getLastModifiedDate().getTime(); if (Files.exists(destFile) && Files.isRegularFile(destFile) && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified && entry.getSize() == Files.size(destFile)) continue; IOUtils.copy(in, destFile); Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified)); } } catch (IOException e) { throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e); } } catch (ArchiveException e) { throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e); } }