Dave's Brain

Browse - Programming Tips - How can I do a "touch" in Java?

Date: 2012oct17
Updated: 2016apr13
Language: Java

Q.  How can I do a "touch" in Java?

A.  Our touch() function is at the bottom of this page. I uses
a few helper functions.

boolean setModifyTimeNow(String filename) { File file = new File(filename); return file.setLastModified(System.currentTimeMillis()); } boolean makeEmptyFile(String filename) { try { OutputStream out = new FileOutputStream(new File(filename)); out.close(); return true; } catch(IOException e) { return false; } } boolean isExists(String filename) { if (filename == null) return false; File file = new File(filename); return file.exists(); } boolean touch(String filename) { if (isExists(filename)) { return setModifyTimeNow(filename); } else { return makeEmptyFile(filename); } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.