List of usage examples for java.io File lastModified
public long lastModified()
From source file:Main.java
public static void main(String[] argv) throws Exception { File f = new File("name.txt"); if (!f.exists()) { System.out.println("File not found."); return;/*from ww w .j a v a2s . co m*/ } if (f.canRead()) System.out.println(" Readable"); else System.out.println(" Not Readable"); if (f.canWrite()) System.out.println(" Writable"); else System.out.println(" Not Writable"); System.out.println(" Last modified on " + new Date(f.lastModified())); long t = Calendar.getInstance().getTimeInMillis(); if (!f.setLastModified(t)) System.out.println("Can't set time."); if (!f.setReadOnly()) System.out.println("Can't set to read-only."); if (f.canRead()) System.out.println(" Readable"); else System.out.println(" Not Readable"); if (f.canWrite()) System.out.println(" Writable"); else System.out.println(" Not Writable"); System.out.println(" Last modified on " + new Date(f.lastModified())); if (!f.setWritable(true, false)) System.out.println("Can't return to read/write."); if (f.canRead()) System.out.println(" Readable"); else System.out.println(" Not Readable"); if (f.canWrite()) System.out.println(" Writable"); else System.out.println(" Not Writable"); }
From source file:de.uniwue.dmir.heatmap.EntryPointIncremental.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) throws IOException, ParseException { DateFormat df = new SimpleDateFormat(DATE_FORMAT); SimpleDateFormat backupDf = new SimpleDateFormat(BACKUP_DATE_FORMAT); String workDir = System.getProperty("workDir", "."); LOGGER.debug("Work dir: {}", workDir); String configDir = System.getProperty("configDir", "."); LOGGER.debug("Config dir: {}", configDir); File seedDir = new File(workDir, SEED_DIR); LOGGER.debug("Seed dir: {}", seedDir); File currentDir = new File(workDir, CURRENT_DIR); LOGGER.debug("Current dir: {}", currentDir); File backupDir = new File(workDir, BACKUP_DIR); LOGGER.debug("Backup dir: {}", backupDir); String initialMinTimeString = System.getProperty("minTime"); LOGGER.debug("Initial minimal time parameter: {}", initialMinTimeString); Date initialMinTime = initialMinTimeString == null ? new Date(0) : df.parse(initialMinTimeString); LOGGER.debug("Initial minimal time: {}", df.format(initialMinTime)); String absoluteMaxTimeString = System.getProperty("maxTime"); LOGGER.debug("Absolute maximal time parameter: {}", absoluteMaxTimeString); Date absoluteMaxTime = absoluteMaxTimeString == null ? new Date() : new SimpleDateFormat(DATE_FORMAT).parse(absoluteMaxTimeString); LOGGER.debug("Absolute maximal time: {}", df.format(absoluteMaxTime)); String incrementalFile = new File("file:" + configDir, INCREMENTAL_FILE).getPath(); String settingsFile = new File("file:" + configDir, HEATMAP_PROCESSOR__FILE).getPath(); LOGGER.debug("Initializing incremental control file: {}", incrementalFile); FileSystemXmlApplicationContext incrementalContext = new FileSystemXmlApplicationContext(incrementalFile); // get point limit int pointLimit = Integer .parseInt(incrementalContext.getBeanFactory().resolveEmbeddedValue("${point.limit}")); LOGGER.debug("Print limit: {}", pointLimit); // get backups to keep int backupsToKeep = Integer .parseInt(incrementalContext.getBeanFactory().resolveEmbeddedValue("${backups.to.keep}")); LOGGER.debug("Backups to keep: {}", pointLimit); LOGGER.debug("Initializing process components (manager and limiter)."); IProcessManager processManager = incrementalContext.getBean(IProcessManager.class); IProcessLimiter processLimiter = incrementalContext.getBean(IProcessLimiter.class); LOGGER.debug("Starting incremental loop."); while (true) { // break as soon as no new points are available // cleanup --- just in case LOGGER.debug("Deleting \"current\" dir."); FileUtils.deleteDirectory(currentDir); // copy from seed to current LOGGER.debug("Copying seed."); seedDir.mkdirs();// ww w . j a v a2s .c o m FileUtils.copyDirectory(seedDir, currentDir); // get min time LOGGER.debug("Getting minimal time ..."); Date minTime = initialMinTime; ProcessManagerEntry entry = processManager.getEntry(); if (entry != null && entry.getMaxTime() != null) { minTime = entry.getMaxTime(); } LOGGER.debug("Minimal time: {}", new SimpleDateFormat(DATE_FORMAT).format(minTime)); // break if we processed all available points (minTime is greater than or equal to absoluteMaxTime) if (minTime.getTime() >= absoluteMaxTime.getTime()) { LOGGER.debug("Processed all points."); break; } // get the maximal time LOGGER.debug("Get maximal time."); // get the time from the newest point in our point range (pointMaxTime) ... Date pointMaxTime = processLimiter.getMaxTime(minTime, pointLimit); // ... and possibly break the loop if no new points are available if (pointMaxTime == null) break; // set the max time and make sure we are not taking to many points // (set max time to the minimum of pointMaxTime and absoluteMaxTime) Date maxTime = pointMaxTime.getTime() > absoluteMaxTime.getTime() ? absoluteMaxTime : pointMaxTime; LOGGER.debug("Maximal time: {}", new SimpleDateFormat(DATE_FORMAT).format(maxTime)); // start process processManager.start(minTime); System.setProperty("minTimestamp", new SimpleDateFormat(DATE_FORMAT).format(minTime)); System.setProperty("maxTimestamp", new SimpleDateFormat(DATE_FORMAT).format(maxTime)); FileSystemXmlApplicationContext heatmapContext = new FileSystemXmlApplicationContext(settingsFile); IHeatmap heatmap = heatmapContext.getBean(HEATMAP_BEAN, IHeatmap.class); ITileProcessor tileProcessor = heatmapContext.getBean(WRITER_BEAN, ITileProcessor.class); heatmap.processTiles(tileProcessor); tileProcessor.close(); heatmapContext.close(); // finish process processManager.finish(maxTime); // move old seed if (backupsToKeep > 0) { FileUtils.moveDirectory(seedDir, new File(backupDir, backupDf.format(minTime))); // minTime is the maxTime of the seed // cleanup backups String[] backups = backupDir.list(DirectoryFileFilter.DIRECTORY); File oldestBackup = null; if (backups.length > backupsToKeep) { for (String bs : backups) { File b = new File(backupDir, bs); if (oldestBackup == null || oldestBackup.lastModified() > b.lastModified()) { oldestBackup = b; } } FileUtils.deleteDirectory(oldestBackup); } } else { FileUtils.deleteDirectory(seedDir); } // move new seed FileUtils.moveDirectory(currentDir, seedDir); } incrementalContext.close(); }
From source file:MainClass.java
public static void main(String args[]) { File f1 = new File("MainClass.java"); System.out.println("File Name:" + f1.getName()); System.out.println("Path:" + f1.getPath()); System.out.println("Abs Path:" + f1.getAbsolutePath()); System.out.println("Parent:" + f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is a directory" + f1.isDirectory()); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified:" + f1.lastModified()); System.out.println("File size:" + f1.length() + " Bytes"); }
From source file:FileDemo.java
public static void main(String args[]) { File f1 = new File("/java/COPYRIGHT"); System.out.println("File Name: " + f1.getName()); System.out.println("Path: " + f1.getPath()); System.out.println("Abs Path: " + f1.getAbsolutePath()); System.out.println("Parent: " + f1.getParent()); System.out.println(f1.exists() ? "exists" : "does not exist"); System.out.println(f1.canWrite() ? "is writeable" : "is not writeable"); System.out.println(f1.canRead() ? "is readable" : "is not readable"); System.out.println("is " + (f1.isDirectory() ? "" : "not" + " a directory")); System.out.println(f1.isFile() ? "is normal file" : "might be a named pipe"); System.out.println(f1.isAbsolute() ? "is absolute" : "is not absolute"); System.out.println("File last modified: " + f1.lastModified()); System.out.println("File size: " + f1.length() + " Bytes"); }
From source file:net.sf.firemox.xml.XmlConfiguration.java
/** * <ul>/*from w ww . j ava2 s . c om*/ * 2 modes: * <li>Update the a MDB for specified TBS against the XML files (main file, * cards and fragments). Arguments are : TBS_NAME</li> * <li>Rebuild completely the MDB for specified TBS. Arguments are : -full * TBS_NAME</li> * </ul> * * @param args * main arguments. */ public static void main(String... args) { options = new Options(); final CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { // Display help info(e.getMessage()); parser.setUsageWidth(80); parser.printUsage(System.out); System.exit(-1); return; } if (options.isVersion()) { // Display version info("Version is " + IdConst.VERSION); System.exit(-1); return; } if (options.isHelp()) { // Display help parser.setUsageWidth(80); parser.printUsage(System.out); System.exit(-1); return; } warning = 0; uncompleted = 0; error = 0; long start = System.currentTimeMillis(); XmlTools.initHashMaps(); MToolKit.tbsName = options.getMdb(); String xmlFile = MToolKit.getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + ".xml", false) .getAbsolutePath(); try { if (options.isForce()) { final File recycledDir = MToolKit.getTbsFile("recycled"); if (!recycledDir.exists() || !recycledDir.isDirectory()) { recycledDir.mkdir(); } parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(), new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false))); } else { // Check the up-to-date state of MDB final File file = MToolKit .getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + "/" + MToolKit.tbsName + ".mdb"); final long lastModifiedMdb; if (file == null) { lastModifiedMdb = 0; } else { lastModifiedMdb = file.lastModified(); } boolean update = false; // Check the up-to-date state of MDB against the main XML file if (MToolKit.getFile(xmlFile).lastModified() > lastModifiedMdb) { // The main XML file is newer than MDB System.out.println("MDB is out of date, " + xmlFile + " is newer"); update = true; } else { final File fragmentDir = MToolKit.getTbsFile(""); for (File frament : fragmentDir.listFiles( (FilenameFilter) FileFilterUtils.andFileFilter(FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.prefixFileFilter("fragment-")))) { if (frament.lastModified() > lastModifiedMdb) { // One card is newer than MDB System.out.println( "MDB is out of date, at least one fragment found : " + frament.getName()); update = true; break; } } if (!update) { // Check the up-to-date state of MDB against the cards final File recycledDir = MToolKit.getTbsFile("recycled"); if (!recycledDir.exists() || !recycledDir.isDirectory()) { recycledDir.mkdir(); } if (recycledDir.lastModified() > lastModifiedMdb) { // The recycled XML file is newer than MDB System.out.println("MDB is out of date, the recycled directory is new"); update = true; } else { for (File card : recycledDir.listFiles((FilenameFilter) FileFilterUtils.andFileFilter( FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.notFileFilter( FileFilterUtils.suffixFileFilter(IdConst.FILE_DATABASE_SAVED))))) { if (card.lastModified() > lastModifiedMdb) { // One card is newer than MDB System.out.println("MDB is out of date, at least one new card found : " + card); update = true; break; } } } } } if (!update) { return; } // Need to update the whole MDB parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(), new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false))); } } catch (SAXParseException e) { // Ignore this error } catch (Exception e) { e.printStackTrace(); } if (warning > 0) { System.out.println("\t" + warning + " warning" + (warning > 1 ? "s" : "")); } if (error > 0) { System.out.println("\t" + error + " error" + (error > 1 ? "s" : "")); System.out.println("Some cards have not been built correctly. Fix them."); } else { System.out.println("\tSuccessfull build"); } System.out.println("\tTime : " + (System.currentTimeMillis() - start) / 1000 + " s"); }
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method./*from w w w. j av a 2 s. c o m*/ */ public static void main(String args[]) { LogUtils.setupUncaughtExceptionHandler(); /* Set timeout for RMI connections - TODO: move to external file */ System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000"); updateRmiHostName(); /* * Set up menu bar for Mac */ System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager"); /* * Set look and feel to 'system' style */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.info("Failed to set system look and feel"); } /* * Set workingDir to a writable folder for storing competitions, settings etc. */ String applicationData = System.getenv("APPDATA"); if (applicationData != null) { workingDir = new File(applicationData, "EventManager"); if (workingDir.exists() || workingDir.mkdirs()) { // redirect logging to writable folder LogUtils.reconfigureFileAppenders("log4j.properties", workingDir); } else { workingDir = new File("."); } } // log version for debugging log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")"); /* * Copy license if necessary */ File license1 = new File("license.lic"); File license2 = new File(workingDir, "license.lic"); if (license1.exists() && !license2.exists()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } if (license1.exists() && license2.exists()) { if (license1.lastModified() > license2.lastModified()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } } /* * Check if run lock exists, if so ask user if it is ok to continue */ if (!obtainRunLock(false)) { int response = JOptionPane.showConfirmDialog(null, "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?", "Run-lock detected", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) obtainRunLock(true); else System.exit(0); } try { LoadWindow loadWindow = new LoadWindow(); loadWindow.setVisible(true); loadWindow.addMessage("Reading settings.."); /* * Read properties from file */ final Properties props = new Properties(); try { Properties defaultProps = PropertiesLoaderUtils .loadProperties(new ClassPathResource("eventmanager.properties")); props.putAll(defaultProps); } catch (IOException ex) { log.error(ex); } props.putAll(System.getProperties()); File databaseStore = new File(workingDir, "comps"); int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port")); loadWindow.addMessage("Loading Peer Manager.."); log.info("Loading Peer Manager"); ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService(); JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat")); peerManager.addDiscoveryService(manualDiscoveryService); monitorNetworkInterfaceChanges(peerManager); loadWindow.addMessage("Loading Database Manager.."); log.info("Loading Database Manager"); DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager); LicenseManager licenseManager = new LicenseManager(workingDir); loadWindow.addMessage("Loading Load Competition Dialog.."); log.info("Loading Load Competition Dialog"); LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager, peerManager); loadCompetitionWindow.setTitle(WINDOW_TITLE); loadWindow.dispose(); log.info("Starting Load Competition Dialog"); while (true) { // reset permission checker to use our license licenseManager.updatePermissionChecker(); GUIUtils.runModalJFrame(loadCompetitionWindow); if (loadCompetitionWindow.getSuccess()) { DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo(); if (!databaseManager.checkLock(info.id)) { String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n" + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n" + "3) Delete the competition from this computer\n" + "4) If possible, reload this competition from another computer on the network\n" + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked."; String title = "WARNING: Potential Data Corruption Detected"; int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)"); if (status == 0) continue; // return to load competition window } SynchronizingWindow syncWindow = new SynchronizingWindow(); syncWindow.setVisible(true); long t = System.nanoTime(); DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash); long dt = System.nanoTime() - t; log.debug(String.format("Initial sync in %dms", TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS))); syncWindow.dispose(); if (loadCompetitionWindow.isNewDatabase()) { GregorianCalendar calendar = new GregorianCalendar(); Date today = calendar.getTime(); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 31); Date endOfYear = new java.sql.Date(calendar.getTimeInMillis()); CompetitionInfo ci = new CompetitionInfo(); ci.setName(info.name); ci.setStartDate(today); ci.setEndDate(today); ci.setAgeThresholdDate(endOfYear); //ci.setPasswordHash(info.passwordHash); License license = licenseManager.getLicense(); if (license != null) { ci.setLicenseName(license.getName()); ci.setLicenseType(license.getType().toString()); ci.setLicenseContact(license.getContactPhoneNumber()); } database.add(ci); } // Set PermissionChecker to use database's license type String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType(); PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType)); TransactionNotifier notifier = new TransactionNotifier(); database.setListener(notifier); MainWindow mainWindow = new MainWindow(); mainWindow.setDatabase(database); mainWindow.setNotifier(notifier); mainWindow.setPeerManager(peerManager); mainWindow.setLicenseManager(licenseManager); mainWindow.setManualDiscoveryService(manualDiscoveryService); mainWindow.setTitle(WINDOW_TITLE); mainWindow.afterPropertiesSet(); TestUtil.setActivatedDatabase(database); // show main window (modally) GUIUtils.runModalJFrame(mainWindow); // shutdown procedures // System.exit(); database.shutdown(); databaseManager.deactivateDatabase(1500); if (mainWindow.getDeleteOnExit()) { for (File file : info.localDirectory.listFiles()) if (!file.isDirectory()) file.delete(); info.localDirectory.deleteOnExit(); } } else { // This can cause an RuntimeException - Peer is disconnected peerManager.stop(); System.exit(0); } } } catch (Throwable e) { log.error("Error in main function", e); String message = e.getMessage(); if (message == null) message = ""; if (message.length() > 100) message = message.substring(0, 97) + "..."; GUIUtils.displayError(null, "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message); System.exit(0); } }
From source file:IndexService.IndexServer.java
public static void main(String[] args) { File stop = new File("/tmp/.indexstop"); File running = new File("/tmp/.indexrunning"); if (args != null && args.length > 0 && args[0].equals("stop")) { try {/*from w w w .j a v a2 s.c om*/ stop.createNewFile(); running.delete(); } catch (IOException e) { e.printStackTrace(); } return; } if (running.exists() && (System.currentTimeMillis() - running.lastModified() < 15000)) { long time = running.lastModified(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } if (running.lastModified() == time) { running.delete(); } else { return; } } if (stop.exists()) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } if (stop.exists()) stop.delete(); } Configuration conf = new Configuration(); IndexServer server = new IndexServer(conf); if (args != null && args.length > 0 && args[0].equals("test")) { server.testmode = true; } server.start(); try { running.createNewFile(); } catch (IOException e) { e.printStackTrace(); } new UserCmdProc(server).start(); while (true) { stop = new File("/tmp/.indexstop"); if (stop.exists()) { server.close(); running.delete(); stop.delete(); break; } try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } running.setLastModified(System.currentTimeMillis()); } }
From source file:Main.java
private static void cleanDir(File dir) { File[] files = dir.listFiles(); for (File file : files) { if (file.lastModified() + 1000 < System.currentTimeMillis()) { //more than a day old file.delete();//from w w w .ja v a 2 s .c o m } } }
From source file:Main.java
public static long getApplicationTime(Context context, PackageInfo info) { String dir = info.applicationInfo.publicSourceDir; File apkFile = new File(dir); return apkFile.lastModified(); }
From source file:Main.java
public static long getFileTime(String dir, String fileName) { File file = new File(dir, fileName); return file.lastModified(); }