File last modified time and current time - java

-I am not using java 8 (Date+Time API...)-I am using Java SE 7
What I am trying to accomplish here is get the last modified time of the directories inside a parent directory in miliseconds , get the current time of the system in miliseconds and then compare them (and delete if...)
This does not seem to work though..
Code:
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = MyParentDirectory.listFiles();
for(File f : subf){
if(f.isDirectory()){
if((Calendar.getInstance().get(Calendar.MILLISECOND) - (f.lastModified() + 1000)) > sec){//The comparison
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length +" folders" + "\n");
}

It look like, there is some problem with File#lastModified() on my Windows, perhaps it is same for you. Try this:
private long getSecondsFromModification(File f) throws IOException {
Path attribPath = f.toPath();
BasicFileAttributes basicAttribs
= Files.readAttributes(attribPath, BasicFileAttributes.class);
return (System.currentTimeMillis()
- basicAttribs.lastModifiedTime().to(TimeUnit.MILLISECONDS))
/ 1000;
}
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = myParentDirectory.listFiles();
for (File f : subf) {
if (f.isDirectory()) {
try {
if (getSecondsFromModification(f) > sec) {
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
} catch (IOException ex) {
System.out.println("Unable to access file " + f.getName() + " informtaion");
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length + " folders" + "\n");
}

Related

PrintStream not creating a file?

I get an error at line 58 which says the file isn't found, but shouldn't the PrintStream have created the file? (Note: No file is created at all.)
Thanks!
WhyDoINeedToAddMoreDetailIAlreadySaidWhatINeedToSay
import java.io.*;
import java.util.*;
import java.text.*;
public class DownloadsFolderCleanup {
public static String directory = "C:\\Users\\User\\Downloads";
public static void main(String[] args) throws FileNotFoundException {
File[] files = (new File(directory)).listFiles();
if (files.length - 1 == 0) {
System.out.println("Downloads folder is already empty!");
}
else {
ArrayList<File> markedFiles = new ArrayList<File>();
int numInstallers = 0, numIncompleteDownloads = 0;
for (File file : files) {
String fileName = file.getName();
if (fileName.substring(fileName.length() - 4,fileName.length()).equals(".exe")) {
if (fileName.toLowerCase().contains("install") || fileName.toLowerCase().contains("setup")) {
markedFiles.add(file);
numInstallers++;
System.out.println('"' + fileName + '"' + " marked for deletion. Reason: Installer");
}
}
if (fileName.length() > 22) {
if (fileName.substring(0,11).equals("Unconfirmed") && fileName.substring(fileName.length() - 11, fileName.length()).equals(".crdownload")) {
markedFiles.add(file);
numIncompleteDownloads++;
System.out.println('"' + fileName + '"' + " marked for deletion. Reason: Incomplete download");
}
}
}
System.out.println("- - - - - - - - - - - - - - - - - - - -");
System.out.println("Total # of files scanned: " + (files.length - 1));
System.out.println("Total # of junk files found: " + markedFiles.size());
System.out.println("Installers found: " + numInstallers);
System.out.println("Incomplete download files found: " + numIncompleteDownloads);
if (markedFiles.size() == 0) {
System.out.println("No junk files were found!");
}
else {
System.out.print("Please confirm removal of all identified files. CANNOT BE UNDONE! Y/N: ");
Scanner input = new Scanner(System.in);
if (input.nextLine().equalsIgnoreCase("Y")) {
System.out.println("All marked files will be permanently deleted in 5 seconds.");
for (int c = 4; c > 0; c--) {
sleep1second();
System.out.println(c + "...");
}
sleep1second();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = new Date();
PrintStream log = new PrintStream(new File(dateFormat.format(date) + " Download Folder Cleanup Log.txt"));
for (File file : markedFiles) {
System.out.println('"' + file.getName() + '"' + " deleted.");
file.delete();
log.println(file.getName());
}
log.close();
}
}
}
System.out.println();
System.out.println("Cleanup process complete!");
}
public static void sleep1second() {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
I'm guessing since your DateFormat "MM/dd/yyyy HH:mm" contains "/" (slashes), that path is invalid and since you're making a file at a path that contains dateFormat.format(date), the file can't be made.
In Windows the following are forbidden characters:
* . " / \ [ ] : ; | = ,

Can't Get Android to Append Data to .txt file

I'm pretty new here, and have been following all I could find on getting my program to append a series of numbers (determined from how often a button was pressed) to a .txt file whenever a timer runs out, but to no avail-I'm not sure what I'm missing...the app starts out by creating a .txt file in the downloads folder with a template in it:
String initialTemplate ="\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\"";
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename+".txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(initialTemplate.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And then when a countdowntimer object finishes and restarts/ends, it triggers the class writeresults() to append the values:
if (CountsRemaining < 1){
textViewTime.setText("00:00:00");
cancel();
writeResults();
finishcount();
} else {
//append data
writeResults();
//Clear all variables
clearCounts();
start();
}
And the important part, to actually write the data, which is what isn't working:
public void writeResults(){
String Message = Count1 + ", " + Count2 + ", " + Count3 + ", " + Count4 + ", " + Count5 + ", " +
Count6 + ", " + Count7 + ", " + Count8 + ", " + Count9 + ", " + Count10 + ", " + Count11 + Count12;
FileWriter writer;
try {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
File file = new File (path + filename+".txt");
writer = new FileWriter(file, true);
writer.append(Message);
writer.append("this is a writing test message");
writer.close();
Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Any idea what I might be missing? Parameters?
The problem is in this line:
File file = new File (path + filename+".txt");
It should be like this, if you look at your first code, when creating file:
File file = new File (path, filename+".txt");

How to add folder to zip

I have my GWT project and I want to upload files to server. I want the following algorithm to work
1) create a folder with the name from "userNumber"
2) write uploaded files to this folder
3) add folder to zip
4) delete folder (if exists)
As I write on the server side I think it is just java problem. Here is my code. I can perform only the first and the second steps, i.e. I can create a folder and write files to this folder.
#Override
public String executeAction(HttpServletRequest request,
List<FileItem> sessionFiles) throws UploadActionException {
String response = "";
userNumber = request.getParameter("userNumber");
File f = new File(ConfAppServer.getRealContextPath() + "/edoc/"
+ userNumber);
if (f.mkdir()) {
System.out.println("Directory Created");
} else {
System.out.println("Directory is not created");
}
for (FileItem item : sessionFiles) {
if (false == item.isFormField()) {
try {
String extension = item.getName().substring(
item.getName().length() - 3);
File file = null;
file = new File(ConfAppServer.getRealContextPath()
+ "/edoc/"
+ userNumber
+ System.getProperty("file.separator")
+ item.getName().substring(0,
item.getName().length() - 4) + "."
+ extension);
item.write(file);
receivedFiles.put(item.getFieldName(), file);
receivedContentTypes.put(item.getFieldName(),
item.getContentType());
response += "<file-" + cont + "-field>"
+ item.getFieldName() + "</file-" + cont
+ "-field>\n";
response += "<file-" + cont + "-name>" + item.getName()
+ "</file-" + cont + "-name>\n";
response += "<file-" + cont + "-size>" + item.getSize()
+ "</file-" + cont + "-size>\n";
response += "<file-" + cont + "-type>"
+ item.getContentType() + "</file-" + cont
+ "type>\n";
} catch (Exception e) {
throw new UploadActionException(e);
}
}
}
ZipUtils appZip = new ZipUtils(userNumber + ".zip",
ConfAppServer.getRealContextPath() + "/edoc/" + userNumber);
appZip.generateFileList(new File(ConfAppServer.getRealContextPath()
+ "/edoc/" + userNumber));
appZip.zipIt(userNumber + ".zip");
f.delete();
removeSessionFileItems(request);
return "<response>\n" + response + "</response>\n";
}
Here you can find my ZipUtils class.
When I try to delete my folder, nothing happens. The delete() method doesn't work. Help me please!!
My question is how to add folder to zip and then delete this folder.
Use java.nio.file. You won't have the hassle of manipulating the ZIP API yourself:
final Path pathToZip = Paths.get("path", "to", "your", "zip");
final URI uri = URI.create("jar:" + pathToZip.toUri());
final Map<String, ?> env = Collections.singletonMap("create", "true");
try (
final FileSystem fs = FileSystems.getFileSystem(uri, env);
) {
// write files into the zip here.
// See javadoc for java.nio.file.Files and FileSystem.getPath()
}
More details on how to use the API here.

Java renameTo() leaving cifs* files on samba mount

I have a linux java program that is reading and writing to a CIFS mounted Windows file share. See code snippet at bottom.
After execution, there are files named "cifs*" left in the directory. If the target directory is on the local file system, the code works like a champ. However, if the target directory is a CIFS mounted Windows file share, I get the left-over files. I'm not sure what configuration changes I need to make to fix. Any help is greatly appreciated.
FileRenameMutex myFileRenameMutex = new FileRenameMutex("/WindowsMount/MoveLock");
class FileRenameMutex
{
// global variables
String lockFileBasename;
String unusedExtension = "_Unused";
String unusedFilename;
String inUseFilename;
String localMachineAddress;
String formattedTime;
// log4j logger for this class
public static Logger logMutex = Logger.getLogger(FileRenameMutex.class.getName());
public FileRenameMutex(String _lockFileBase) {
this.lockFileBasename = _lockFileBase;
logMutex.debug("FileRenameMutex: Constructor, with file " + lockFileBasename + " user = " + System.getProperty("user.name"));
try {
localMachineAddress = InetAddress.getLocalHost().getHostAddress();
//localMachineAddress = InetAddress.getLocalHost().getHostName();
} catch ( Exception e ) {
localMachineAddress = "UNKNOWN_HOST";
logMutex.error(" Could not determine host address. " + e.getMessage());
}
// set the file names
unusedFilename = lockFileBasename + unusedExtension;
inUseFilename = lockFileBasename + "_" + localMachineAddress;
logMutex.debug(" Local machine = " + localMachineAddress);
logMutex.debug(" Unused file name = " + this.unusedFilename);
logMutex.debug(" In Use file name = " + this.inUseFilename);
}
public boolean tryAcquire() throws InterruptedException {
boolean returnVal = false;
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
formattedTime = new Date().toString();
String inUseText = "This file created by the Alfresco cron job to MoveFileAndCreateDir "
+ "(move files from Unfiled to Filed folders).\n"
+ "Running on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
// attempt to rename file
logMutex.debug(" Attempting to rename mutex file " + unusedFilename + " to " + inUseFilename);
if ( unusedFile.renameTo(inUseFile) ) {
logMutex.debug(" Rename to inUse successful");
out.write(inUseText);
out.flush();
out.close();
returnVal = true; // lock was acquired
} else {
// System.out.println("Rename to inUse failed");
logMutex.error(" Rename of " + unusedFilename + " to " + inUseFilename + " failed in tryAcquire().");
}
} catch ( Exception e ) {
throw new InterruptedException("Error acquiring lock in tryAcquire(): " + e.getMessage());
}
return returnVal;
}
public void release() {
File unusedFile = new File(unusedFilename);
File inUseFile = new File(inUseFilename);
String unusedText = "This file was last by the Alfresco cron job to MoveFileAndCreateDir "
+ "Ran on " + localMachineAddress + "\n Started at " + formattedTime + "\n";
try {
FileWriter fstream = new FileWriter(inUseFile);
BufferedWriter out = new BufferedWriter(fstream);
out.write(unusedText);
out.flush();
out.close();
// attempt to rename file
logMutex.debug(" Attempting to rename active mutex file " + inUseFilename + " back to " + unusedFilename);
if ( inUseFile.renameTo(unusedFile) ) {
logMutex.debug(" Rename back to unused successful");
} else {
logMutex.error(" Rename of " + inUseFilename + " to " + unusedFilename + " failed in release().");
}
} catch ( Exception e ) {
logMutex.error("Error resetting lock file in release(): " + e.getMessage());
}
} // release()
} // end of class FileRenameMutex

Converting working code into a recursive method

Hi guys I needed to create a method to display current directory, files, subdirectories and the files of those subdirectories given a file the user has to choose. I accomplished the task and the fallowing code is printing the appropriated output. It is printing from the f.getParentFile() down, that is what want. Now I want to use recursion instead. I am trying to learn the concept of recursion. I know you need a base case and then your inductive step, but when I try to modify my code into recursive I get an infinite loop when it hits the first subdirectory. Any feedback will be appreciated.
NON-Recursive Working code
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
File[] listFiles = list[i].getAbsoluteFile().listFiles();
for (int j = 0; j < listFiles.length; j++)
{
System.out.println("\t\tSubdirectory files: " + listFiles[j].getName() + "\tsize :" + (listFiles[j].length()/1024) + "KB" );
}
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
Attempting Recursion
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
listFiles(list[i].getAbsoluteFile());
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
It is really really simple :)
public static void main(String[] args) {
filesInFolder("./");
}
public static void filesInFolder(String filename) {
File dir = new File(filename);
for (File child : dir.listFiles()) {
System.out.println(child.getAbsolutePath());
if (child.isDirectory()){
filesInFolder(child.getAbsolutePath());
}
}
}

Categories