Java Code Examples for java.io.File.setLastModified()

The following are Jave code examples for showing how to use setLastModified() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: q-mail   File: FileHelper.java   View Source Code Vote up 6 votes
public static void touchFile(final File parentDir, final String name) {
    final File file = new File(parentDir, name);
    try {
        if (!file.exists()) {
            if (!file.createNewFile()) {
                Timber.d("Unable to create file: %s", file.getAbsolutePath());
            }
        } else {
            if (!file.setLastModified(System.currentTimeMillis())) {
                Timber.d("Unable to change last modification date: %s", file.getAbsolutePath());
            }
        }
    } catch (Exception e) {
        Timber.d(e, "Unable to touch file: %s", file.getAbsolutePath());
    }
}
 
Example 2
Project: Pogamut3   File: TestUnpackMojo.java   View Source Code Vote up 6 votes
public void assertUnpacked( ArtifactItem item, boolean overWrite )
    throws InterruptedException, MojoExecutionException
{

    File unpackedFile = getUnpackedFile( item );

    Thread.sleep( 100 );
    // round down to the last second
    long time = System.currentTimeMillis();
    time = time - ( time % 1000 );
    unpackedFile.setLastModified( time );

    assertEquals( time, unpackedFile.lastModified() );
    mojo.execute();

    if ( overWrite )
    {
        assertTrue( time != unpackedFile.lastModified() );
    }
    else
    {
        assertEquals( time, unpackedFile.lastModified() );
    }
}
 
Example 3
Project: android-project-gallery   File: LimitedDiscCache.java   View Source Code Vote up 6 votes
@Override
public void put(String key, File file) {
	int valueSize = getSize(file);
	int curCacheSize = cacheSize.get();

	while (curCacheSize + valueSize > sizeLimit) {
		int freedSize = removeNext();
		if (freedSize == INVALID_SIZE) break; // cache is empty (have nothing to delete)
		curCacheSize = cacheSize.addAndGet(-freedSize);
	}
	cacheSize.addAndGet(valueSize);

	Long currentTime = System.currentTimeMillis();
	file.setLastModified(currentTime);
	lastUsageDates.put(file, currentTime);
}
 
Example 4
Project: convertigo-eclipse   File: XslRuleEditor.java   View Source Code Vote up 6 votes
public void propertyChanged(Object source, int propId) {
	// When a property from the xslEditor Changes, walk the list all the listeners and notify them.
	Object listeners[] = listenerList.getListeners();
	for (int i = 0; i < listeners.length; i++) {
		IPropertyListener listener = (IPropertyListener) listeners[i];
		listener.propertyChanged(this, propId);
	}

	if (propId == IEditorPart.PROP_DIRTY) {
		if (!xmlEditor.isDirty()) {
			// We changed from Dirty to non dirty ==> User has saved so,
			// launch Convertigo engine

			// "touch" the parent style sheet ==> Convertigo engine will
			// recompile it
			
			IPath path;
			path = file.getRawLocation();
			path = path.append("../../" + parentStyleSheetUrl);
			File parentFile = path.toFile();
			parentFile.setLastModified(System.currentTimeMillis());
		}
	}
}
 
Example 5
Project: incubator-netbeans   File: Stamps.java   View Source Code Vote up 6 votes
private static void discardCachesImpl(AtomicLong al) {
    File user = Places.getUserDirectory();
    long now = System.currentTimeMillis();
    if (user != null) {
        File f = new File(user, ".lastModified");
        if (f.exists()) {
            f.setLastModified(now);
        } else {
            f.getParentFile().mkdirs();
            try {
                f.createNewFile();
            } catch (IOException ex) {
                LOG.log(Level.WARNING, "Cannot create " + f, ex);
            }
        }
    }
    if (al != null) {
        al.set(now);
    }
}
 
Example 6
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 6 votes
@SuppressWarnings("CallToThreadDumpStack")
public static boolean packInternally(final File source,
        final File target) throws IOException {
    try {
        JarFile jarFile = new JarFile(source);
        FileOutputStream outputStream = new FileOutputStream(target);

        
        String output = "Packing jarFile: " + jarFile + " to " + target;
        if (project != null) {
            project.log("            " + output);
        } else {
            System.out.println(output);
        }

        packer.pack(jarFile, outputStream);

        jarFile.close();
        outputStream.close();
        target.setLastModified(source.lastModified());
    } catch (IOException exc) {
        exc.printStackTrace();
        return false;
    }
    return true;
}
 
Example 7
Project: Moenagade   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * Internal copy directory method.
 * 
 * @param srcDir  the validated source directory, must not be <code>null</code>
 * @param destDir  the validated destination directory, must not be <code>null</code>
 * @param filter  the filter to apply, null means copy all directories and files
 * @param preserveFileDate  whether to preserve the file date
 * @param exclusionList  List of files and directories to exclude from the copy, may be null
 * @throws IOException if an error occurs
 * @since Commons IO 1.1
 */
private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
        boolean preserveFileDate, List<String> exclusionList) throws IOException {
    // recurse
    File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
    if (srcFiles == null) {  // null if abstract pathname does not denote a directory, or if an I/O error occurs
        throw new IOException("Failed to list contents of " + srcDir);
    }
    if (destDir.exists()) {
        if (destDir.isDirectory() == false) {
            throw new IOException("Destination '" + destDir + "' exists but is not a directory");
        }
    } else {
        if (!destDir.mkdirs() && !destDir.isDirectory()) {
            throw new IOException("Destination '" + destDir + "' directory cannot be created");
        }
    }
    if (destDir.canWrite() == false) {
        throw new IOException("Destination '" + destDir + "' cannot be written to");
    }
    for (File srcFile : srcFiles) {
        File dstFile = new File(destDir, srcFile.getName());
        if (exclusionList == null || !exclusionList.contains(srcFile.getCanonicalPath())) {
            if (srcFile.isDirectory()) {
                doCopyDirectory(srcFile, dstFile, filter, preserveFileDate, exclusionList);
            } else {
                doCopyFile(srcFile, dstFile, preserveFileDate);
            }
        }
    }

    // Do this last, as the above has probably affected directory metadata
    if (preserveFileDate) {
        destDir.setLastModified(srcDir.lastModified());
    }
}
 
Example 8
Project: incubator-netbeans   File: TestFileUtils.java   View Source Code Vote up 5 votes
/**
     * Make sure the timestamp on a file changes.
     * @param f a file to touch (make newer)
     * @param ref if not null, make f newer than this file; else make f newer than it was before
     */
    @SuppressWarnings("SleepWhileInLoop")
    public static void touch(File f, File ref) throws IOException, InterruptedException {
        long older = f.lastModified();
        if (ref != null) {
            older = Math.max(older, ref.lastModified());
        } else {
            older = Math.max(older, System.currentTimeMillis());
        }
        int maxPause = 9999;
        /* XXX consider this (as yet untested):
        long curr = System.currentTimeMillis();
        if (older > curr + maxPause) {
            throw new IllegalArgumentException("reference too far into the future, by " + (older - curr) + "msec");
        }
         */
        for (long pause = 1; pause < maxPause; pause *= 2) {
            Thread.sleep(pause);
            f.setLastModified(System.currentTimeMillis() + 1);  // plus 1 needed for FileObject tests (initially FO lastModified is set to currentTimeMillis)
            if (f.lastModified() > older) {
                while (f.lastModified() >= System.currentTimeMillis()) {
//                    LOG.log(Level.INFO, "Modification time is in future {0}", System.currentTimeMillis());
                    Thread.sleep(10);
                }
                return;
            }
        }
        Assert.fail("Did not manage to touch " + f);
    }
 
Example 9
Project: browser   File: SearchAdapter.java   View Source Code Vote up 5 votes
private File downloadSuggestionsForQuery(String query) {
	File cacheFile = new File(mContext.getCacheDir(), query.hashCode() + ".sgg");
	if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {
		return cacheFile;
	}
	if (!isNetworkConnected(mContext)) {
		return cacheFile;
	}
	try {
		URL url = new URL("http://google.com/complete/search?q=" + query
				+ "&output=toolbar&hl=en");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoInput(true);
		connection.connect();
		InputStream in = connection.getInputStream();

		if (in != null) {
			FileOutputStream fos = new FileOutputStream(cacheFile);
			int buffer;
			while ((buffer = in.read()) != -1) {
				fos.write(buffer);
			}
			fos.flush();
			fos.close();
		}
		cacheFile.setLastModified(System.currentTimeMillis());
	} catch (Exception e) {
		e.printStackTrace();
	}
	return cacheFile;
}
 
Example 10
Project: starcor.xul   File: XulFileCache.java   View Source Code Vote up 5 votes
private void saveFileToCache(File tempFile, long putTime, XulCacheModel data) {
	File file = new File(_cacheDir, data.getKey());
	tempFile.renameTo(file);
	file.setLastModified(putTime);
	data.setLastAccessTime(putTime);
	data.setData(file);
}
 
Example 11
Project: mvvm-clean   File: ACache.java   View Source Code Vote up 5 votes
private File get(String key) {
    File file = newFile(key);
    Long currentTime = System.currentTimeMillis();
    file.setLastModified(currentTime);
    lastUsageDates.put(file, currentTime);

    return file;
}
 
Example 12
Project: ats-framework   File: LocalFileSystemOperations.java   View Source Code Vote up 5 votes
@Override
public void setFileModificationTime(
                                     String sourceFile,
                                     long lastModificationTime ) {

    File file = new File(sourceFile);
    checkFileExistence(file);

    if (!file.setLastModified(lastModificationTime)) {
        throw new FileSystemOperationException("Could not set last modification time for file '"
                                               + sourceFile + "'");
    }
}
 
Example 13
Project: OpenEyesReading-android   File: ACache.java   View Source Code Vote up 5 votes
private File get(String key) {
    File file = newFile(key);
    Long currentTime = System.currentTimeMillis();
    file.setLastModified(currentTime);
    lastUsageDates.put(file, currentTime);

    return file;
}
 
Example 14
Project: Ency   File: AppACache.java   View Source Code Vote up 5 votes
private File get(String key) {
    File file = newFile(key);
    Long currentTime = System.currentTimeMillis();
    file.setLastModified(currentTime);
    lastUsageDates.put(file, currentTime);

    return file;
}
 
Example 15
Project: Pogamut3   File: TestUnpackMojo.java   View Source Code Vote up 5 votes
public void testUnpackOverWriteIfNewer()
    throws IOException, MojoExecutionException, InterruptedException
{
    stubFactory.setCreateFiles( true );
    Artifact artifact = stubFactory.getSnapshotArtifact();
    artifact.getFile().setLastModified( System.currentTimeMillis() - 2000 );

    ArtifactItem item = new ArtifactItem( artifact );

    ArrayList list = new ArrayList( 1 );
    list.add( item );
    mojo.setArtifactItems( list );
    mojo.setOverWriteIfNewer( true );
    mojo.execute();
    File unpackedFile = getUnpackedFile( item );

    // round down to the last second
    long time = System.currentTimeMillis();
    time = time - ( time % 1000 );
    // go back 10 more seconds for linux
    time -= 10000;
    // set to known value
    unpackedFile.setLastModified( time );
    // set source to be newer
    artifact.getFile().setLastModified( time + 4000 );

    // manually set markerfile (must match getMarkerFile in
    // DefaultMarkerFileHandler)
    File marker = new File( mojo.getMarkersDirectory(), artifact.getId().replace( ':', '-' ) + ".marker" );
    marker.setLastModified( time );

    assertTrue( time == unpackedFile.lastModified() );
    mojo.execute();
    assertTrue( time != unpackedFile.lastModified() );
}
 
Example 16
Project: guava-mock   File: FilesTest.java   View Source Code Vote up 5 votes
public void testTouchTime() throws IOException {
  File temp = createTempFile();
  assertTrue(temp.exists());
  temp.setLastModified(0);
  assertEquals(0, temp.lastModified());
  Files.touch(temp);
  assertThat(temp.lastModified()).isNotEqualTo(0);
}
 
Example 17
Project: JWebAssembly   File: SpiderMonkey.java   View Source Code Vote up 4 votes
/**
 * Check if there is a new version of the script engine
 * 
 * @throws IOException
 *             if any error occur
 */
private void download() throws IOException {
    boolean is32 = "32".equals( System.getProperty( "sun.arch.data.model" ) );
    String fileName;
    final String os = System.getProperty( "os.name", "" ).toLowerCase();
    if( os.contains( "windows" ) ) {
        fileName = is32 ? "win32" : "win64";
    } else if( os.contains( "mac" ) ) {
        fileName = is32 ? "mac" : "mac64";
    } else if( os.contains( "linux" ) ) {
        fileName = is32 ? "linux-i686" : "linux-x86_64";
    } else {
        throw new IllegalStateException( "Unknown OS: " + os );
    }
    File target = new File( System.getProperty( "java.io.tmpdir" ) + "/SpiderMonkey" );
    URL url = new URL( "https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central/jsshell-" + fileName
                    + ".zip" );
    System.out.println( "\tDownload: " + url );
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    if( target.exists() ) {
        System.out.println( "\tUP-TP-DATE" );
        conn.setIfModifiedSince( target.lastModified() );
    }
    InputStream input = conn.getInputStream();
    command = target.getAbsolutePath() + "/js";
    if( conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED ) {
        return;
    }
    ZipInputStream zip = new ZipInputStream( input );
    long lastModfied = conn.getLastModified();
    do {
        ZipEntry entry = zip.getNextEntry();
        if( entry == null ) {
            break;
        }
        if( entry.isDirectory() ) {
            continue;
        }
        File file = new File( target, entry.getName() );
        file.getParentFile().mkdirs();

        Files.copy( zip, file.toPath(), StandardCopyOption.REPLACE_EXISTING );
        file.setLastModified( entry.getTime() );
        if( "js".equals( file.getName() ) ) {
            file.setExecutable( true );
        }
    } while( true );
    target.setLastModified( lastModfied );
}
 
Example 18
Project: HeadlineNews   File: CacheUtils.java   View Source Code Vote up 4 votes
private void updateModify(final File file) {
    Long millis = System.currentTimeMillis();
    file.setLastModified(millis);
    lastUsageDates.put(file, millis);
}
 
Example 19
Project: convertigo-engine   File: MobileResourceHelper.java   View Source Code Vote up 4 votes
private void writeStringToFile(File file, String content) throws IOException {
	long lastModified = file.exists() ? file.lastModified() : System.currentTimeMillis();
	FileUtils.writeStringToFile(file, content, "UTF-8");
	file.setLastModified(lastModified);
}
 
Example 20
Project: lams   File: FileUtils.java   View Source Code Vote up 3 votes
/**
 * Implements the same behaviour as the "touch" utility on Unix. It creates
 * a new file with size 0 or, if the file exists already, it is opened and
 * closed without modifying it, but updating the file date and time.
 * <p>
 * NOTE: As from v1.3, this method throws an IOException if the last
 * modified date of the file cannot be set. Also, as from v1.3 this method
 * creates parent directories if they do not exist.
 *
 * @param file  the File to touch
 * @throws IOException If an I/O problem occurs
 */
public static void touch(File file) throws IOException {
    if (!file.exists()) {
        OutputStream out = openOutputStream(file);
        IOUtils.closeQuietly(out);
    }
    boolean success = file.setLastModified(System.currentTimeMillis());
    if (!success) {
        throw new IOException("Unable to set the last modification time for " + file);
    }
}