# File Watch

## Recommended Posts

Hey guys, what's up. I need to write a script that monitors a folder containing video files. Based on the filenames, I will need to do a variety of things (e.g. truncate filename to specified length, append an incremental number sequence to distinguish like-titled files, delete a file if it were to meet certain criteria). Anyone want to help get me started? I need to use JSPs to accomplish this.

##### Share on other sites
Hey guys, what's up. I need to write a script that monitors a folder containing video files. Based on the filenames, I will need to do a variety of things (e.g. truncate filename to specified length, append an incremental number sequence to distinguish like-titled files, delete a file if it were to meet certain criteria). Anyone want to help get me started? I need to use JSPs to accomplish this.
The Java File class is where you'll want to start. I looked around a bit but could only find this and this on what you are specifically trying to accomplish.Hope that can get you started.

##### Share on other sites

Anyone see a reason this won't work?

import java.io.File;public class scan{	public static void main(String[] args)	{		File myDir = new File("C:\\Documents and Settings\\vid\\Desktop\\testfolder");		String[] files = myDir.list();		final int maxLength = 35;		int incrementalNumber = 0;		        //for (String file : files)        for (int i = 0; i < files.length; i++)        {        	String fileName = files[i].toString();System.out.println("fileName: " + fileName);        	        	if(fileName.length() > maxLength)        	{        		File oldfile = new File(fileName);        		        		String newFileName = fileName.substring(0, 28);        		String extension = fileName.substring(fileName.length() - 4,         				fileName.length());        		newFileName += incrementalNumber + extension;System.out.println("newFileName: " + newFileName);        		        		File newFile = new File(newFileName);        		System.out.println( oldfile.renameTo(newFile) ); // **returns false every time**        		incrementalNumber++;        	}			System.out.println("---------------------------");        }	}}

All the files are readable and there are no other files in that directory with the same name as the new one. I don't know why or how this is not working, and I do not know how I could go about debugging or testing to find out either. Any help would be much appreciated.

##### Share on other sites

This will need to setup as a CRON job and set to run every n minutes.This should get you started

import java.io.*;public interface IMonitor {	void scan();	void renameFiles();	void deleteFiles();}public class VideoMonitor implements IMonitor {	private String _directory;	private String[] _files;	private int _maxFilenameLength;		public VideoMonitor(String directory, int maxFilenameLength) {		_directory = directory;		_maxFilenameLength = maxFilenameLength	}		public void scan() {		//scan directory		File f = new File(_directory);				//dump file names to array		_files = f.list();	}		public void renameFiles() {		File f = null;				//iterate file names		for(int i=0; i<_files.length; i++) {			f = new File(_files[i]);						//make sure it's a file			if(f.isFile()) {				if(f.getName().length > _maxFilenameLength) {					//truncate file name					File newFile = File(_directory + 						f.getName().substring(0, _maxFilenameLength));										//make sure the name is unique					int counter = 0;					while(newFile.exists()) {						counter++;						newFile = new File(_directory + 						f.getName().substring(0, _maxFilenameLength-1) +						counter);					}										//update file name list					_files[i] = newFile.getAbsoluetPath();										//rename file									f.renameTo(newFile);				}			}		}	}		public void deleteFiles() {		File f = null;		for(int i=0; i<_files.length; i++) {			f = new File(_files[i]);			if(some condition) {				f.delete();			}		}	}}//usageIMonitor monitor = new VideoMonitor("/path/to/your/videos/");monitor.scan();monitor.renameFiles();monitor.deleteFiles();

##### Share on other sites

ASPNetGuy - Thank you! It's funny, I didn't think I was gonna get a response in this forum, so I went ahead and figured it out on my own over the past couple of days. I came up with an almost identical solution. One difference, though. With my implementation of the renameTo() method, it would return false, not actually renaming the file. So, just to make it work and get it usable, I ended up writing all the data to another (already renamed) file using a buffered writer and reader, and then deleting the wrongly named original. It works, but dang is it slow! As soon as I'm done with this batch right now, I'm gonna rewrite that part of the code and see if I can get renameTo() to work for me. Again, thank you so much!

##### Share on other sites

It has been awhile since I did any Java but I use C# everyday and they have a lot of similarities. That code is untested and is likely to have some wrong syntax.

##### Share on other sites
It has been awhile since I did any Java but I use C# everyday and they have a lot of similarities. That code is untested and is likely to have some wrong syntax.
Here's the implementation I used, posted here for posterity's sake.
import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.util.Date;import java.text.Format;import java.text.SimpleDateFormat;public class filename_listing{	public static void main(String[] args) throws IOException	{		/****************************** DO NOT FORGET THE DOUBLE SLASHES! ******************************/		/**************** DO NOT FORGET THE DOUBLE SLASHES AT THE END OF THE PATH NAME! ****************/		/*~~ //||||||||||||||||||||||||||||||||||/\/~~~---~~~\/\||||||||||||||||||||||||||||||||||\\ ~~*/				String pathName = "E:\\to convert\\";				String logPathName = "C:\\Documents and Settings\\vid\\Desktop\\test-batch\\";		/*~~ //||||||||||||||||||||||||||||||||||\/\~~~---~~~/\/||||||||||||||||||||||||||||||||||\\ ~~*/		/**************** DO NOT FORGET THE DOUBLE SLASHES AT THE END OF THE PATH NAME! ****************/		/****************************** DO NOT FORGET THE DOUBLE SLASHES! ******************************/				// Declare and instantiate all needed variables		File myDir = new File(pathName);		String[] files = myDir.list();				final int maxLength = 35;				int incrementalNumber = 0;		int files_deleted = 0;		Format formatter = new SimpleDateFormat("MM-dd-yy");		Date now = new Date();				BufferedWriter logOut = new BufferedWriter( new FileWriter(logPathName + formatter.format(now) + "_truncation_log.txt") );				BufferedWriter logOut2 = new BufferedWriter( new FileWriter(logPathName + formatter.format(now) + "_list_of_files_log.csv") );		String[] filter_words = {"forecast", "ohio_weather"};				logOut.write("   LOG OF CHANGES MADE TO VIDEOS\n");		logOut.write("------------------------------------------\n");		logOut.write("   ------------------------------------   \n");						try		{			// Loop through all files in directory			for (int i = 0; i < files.length; i++)			{				String fileName = files[i].toString().toLowerCase();								// Test each file for a match to any word in the 'filter_words' array				for (int a = 0; a < filter_words.length; a++)				{					String current_word = filter_words[a];										// If it matches, delete it					if ( fileName.indexOf(current_word) != -1 )					{						File file_to_delete = new File( pathName + files[i].toString() );						file_to_delete.delete();						files_deleted++;												break;					}				}			}						// Log the total number of deleted files			logOut.write("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");			logOut.write("TOTAL NUMBER OF FILES DELETED: " + files_deleted);			logOut.write("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n");		}		catch (Exception e)		{			System.out.println("\nError deleting files:");			System.out.println(e);		}				// Reset the list of files now that some have been deleted		myDir = new File(pathName);		files = myDir.list();				// Now comes the renaming of the files		try		{			// Loop through all files in directory			for (int i = 0; i < files.length; i++)			{				String fileName = files[i].toString();								// If its filename is too long, cut it down				if(fileName.length() > maxLength)				{					File f = new File(pathName + fileName);										// LOG OLD FILE NAME!					logOut.write("OLD FILE NAME: " + fileName + "\n");										// Cut off excess, but keep file extension					String possibleFileName = fileName.substring(0, 29);					String extension = fileName.substring(fileName.length() - 4, fileName.length());					possibleFileName += extension;										File temp2 = new File(pathName + possibleFileName);										// If the 'new' filename already exists, try to make it unique					while ( temp2.exists() )					{						String temp = fileName.substring(0, 29) + incrementalNumber + extension;													incrementalNumber++;						temp2 = new File(pathName + temp);						possibleFileName = temp;					}										// It's a unique filename, so rename the original now					f.renameTo(temp2);					// LOG NEW FILE NAME!					logOut.write("NEW FILE NAME: " + possibleFileName + "\n");					logOut.write("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");				}								// Make sure that every time we touch a file, we dump the recorded info into the log				logOut.flush();			}						logOut.close();			logOut = null;		}		catch (FileNotFoundException fnfe)		{System.out.println(fnfe);}		catch (Exception e)		{			System.out.println("\nError renaming files:");			System.out.println(e);		}		// Just makin' sure yo		finally		{			try			{								if (logOut != null)				{logOut.close();}			}			catch (Exception e)			{				System.out.println("\nUnknown error:");				System.out.println(e);			}		}				// Reset the list of files now that some have been renamed		myDir = new File(pathName);		files = myDir.list();				// Create a log of all remaining files within the directory		try		{			for (int i = 0; i < files.length; i++)			{				String fileName = files[i].toString();							if ( i == (files.length - 1) )				{logOut2.write(fileName);}				else				{logOut2.write(fileName + ", ");}			}						logOut2.close();			logOut2 = null;		}		catch (Exception e)		{			System.out.println("Error in reading list of files:");			System.out.println(e);		}	}}

Some of that can be cleaned up and made more efficient, and some of the code can be combined with other code so that multiple steps can be condensed to one. I know all that, but this approach worked best for my context. Anyways, hope this helps some people out.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.