Thread: Folder Watching
View Single Post
  #7 (permalink)  
Old 04-07-2008, 04:35 PM
JavaPF's Avatar
JavaPF JavaPF is offline
mmm.. coffee
 
7 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,581
Thanks: 103
Thanked 93 Times in 86 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Stressed
Default Re: Folder Watching

Hey Jazz,

Here is a crude example for you. You will have to edit the code to check dir1 every minute or put it into a loop or something.

Currently this will take the text files from dir1 and re-create them into dir2.

You will also need to add code to delete the files from dir1 after creation.

Java Code
import java.io.File;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
 
public class ListFiles 
{ 
 public static String path1;
 public static String path2;
 public static String files;
 public static String fileName;
 
 public static void main(String[] args) throws Exception
{
   path1 = "/dir1/"; 
   path2 = "/dir2/";
 
  File folder = new File(path1);
  File[] listOfFiles = folder.listFiles(); 
  for (int i = 0; i < listOfFiles.length; i++) 
  {
 
   if (listOfFiles[i].isFile()) 
   {
   files = listOfFiles[i].getName();
       if (files.endsWith(".txt") || files.endsWith(".TXT"))
       {
 
          System.out.println(files);
 
          try
          {
          FileInputStream in = new FileInputStream(path1 + files);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
 
     Writer output;
     File file1 = new File(path2 + files);
     String newline = System.getProperty("line.separator"); 
     output = new BufferedWriter(new FileWriter(file1));
 
          while((strLine = br.readLine())!= null)
          {
           //Write contents of text file
           output.write(strLine);
           output.write(newline);
          //System.out.println(strLine);
          }
 
           output.close();
 
          }catch(Exception e){
           System.out.println(e);
          }
 
        }
       }
  }
}
}
Let me know if you get stuck and ill try to finish this off. I'm away from the computer now though so thought id post this quickly.
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote