Solved

PLease:  I need program which moves files from one directory to another and renames each file to a unique name before placing it to another directory I m handling csv files.

Posted on 2006-11-16
9
174 Views
Last Modified: 2010-03-31
PLease:  I need program which moves files from one directory to another and renames each file to a unique name before placing it to another directory I m handling csv files.

Files that come in directory where they shoudl be moved from have 10 or more caracters xxxxxxxxxxxxxx.csv  and when they are moved they should be assigned a unique file name of max 8 caracters. Pelase help.
0
Comment
Question by:dm98101
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 43 total points
ID: 17957040
0
 
LVL 23

Assisted Solution

by:Ajay-Singh
Ajay-Singh earned 41 total points
ID: 17957377
try this:


    public void move(File sourceDir, File destDir) throws IOException {
        File[] all = sourceDir.listFiles();
        if (null == all || 0 == all.length)
            return;

        for (int i = 0; i < all.length; i++) {
            String name = all[i].getName();
            int idx = name.lastIndexOf('.');
            String extension = null;
            if (idx > 0)
                extension = name.substring(idx + 1);

            File finalFile = new File(destDir, System.currentTimeMillis() + (extension == null ? "" : ("." + extension)));
            while (!finalFile.exists())
                finalFile = new File(destDir, System.currentTimeMillis() + (extension == null ? "" : ("." + extension)));

            if (!all[i].renameTo(finalFile))
                throw new IOException("Rename failed.");
        }
    }
0
 
LVL 2

Expert Comment

by:saintsairforce
ID: 17958620
Hee are some functions I used to accomplish something simular to what you want.       

import java.io.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

/*******************************************************************************
      loadHTML(String)
      
      This loads html files into the home directory
      *******************************************************************************/
      private void loadHTML(String home)
      {
            String fileDiscription="";
            File intputFile,outputFile;
            
            getFiles();
            
            if(cancelFlag!=JFileChooser.CANCEL_OPTION)
            {
                  for(int knt=0;knt<selectedFiles.length;knt++)
                  {
                        intputFile = new File(directory+"\\"+selectedFiles[knt]);            //sets the location of the input file
                        outputFile = new File(home+selectedFiles[knt]);                              //sets the location of the output file
                        
                        try
                        {      
                              copyFile(intputFile,outputFile,home);
                  }
                        catch(IOException e)
                        {
                              JOptionPane.showMessageDialog(null,"Unable to upload "+selectedFiles[knt],"ERROR",JOptionPane.ERROR_MESSAGE);
                        }
                  }
            }
      }
      
      /*******************************************************************************
      getFiles()
      
      This opens a JFileChooser and allows the user to browse their computer for files.
      *******************************************************************************/
      
      private void getFiles()
      {
            JFileChooser chooser = new JFileChooser();

            chooser.setAcceptAllFileFilterUsed(false);                  //does not allow user to use the AllFiles type option.
            chooser.addChoosableFileFilter(new htmlFilter());      //filters selection to only allow html and htm files
            chooser.setMultiSelectionEnabled(true);                   //Allows the user to select multiple files

            try      //this sets the look and feel of the file chooser to the currently selected look and feel
            {
                  UIManager.setLookAndFeel(UserMenu.looks[UserMenu.lookNumber].getClassName());
                  SwingUtilities.updateComponentTreeUI(this);
            }
            catch(Exception e)
            {
                  new ErrorLogger("Error getFiles() - fileLoader.java:    "+e);
            }
            
            cancelFlag = chooser.showOpenDialog(this);
            
            directory = (chooser.getCurrentDirectory()).toString();      //gets the current directory
            
            File tempFiles[] = chooser.getSelectedFiles();
            
            selectedFiles = new String[tempFiles.length];
            
            for(int knt=0;knt<tempFiles.length;knt++)
            {
                  selectedFiles[knt] = tempFiles[knt].getName();
            }
      }

/*******************************************************************************
      copyFile(File, File, String)
      
      This method copies the input file to the selected output directory.
      *******************************************************************************/
      
      public void copyFile(File inputFile, File outputFile, String directory) throws IOException
      {
            if((new File(directory).mkdir()));             //creates home directory if needed
            
            InputStream inStream = new FileInputStream(inputFile);
            OutputStream outStream = new FileOutputStream(outputFile);
            
            byte[] buffer = new byte[1024];
            int length;
            
            while ((length = inStream.read(buffer)) > 0)
            {
                  outStream.write(buffer, 0, length);
            }
            
            inStream.close();
            outStream.close();
      }

Hopes this helps

Cheers,
Ricky
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:dm98101
ID: 17963281
Hej Ajay-Singh

How to use this program????
what to writte in sourceDir like C:\file1    just for test or?  
0
 

Author Comment

by:dm98101
ID: 17963581
Hej saintsairforce

I need this for *.csv files????  to be moved as they come to another directory with a unique name with no more than 8 caracters. and they should dissapear from source directory
0
 
LVL 2

Assisted Solution

by:saintsairforce
saintsairforce earned 41 total points
ID: 17975120
Here is an updated program    

import java.io.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

/*******************************************************************************
     loadHTML(String)
     
     This loads html files into the home directory
     *******************************************************************************/
     private void loadCSV(String home)
     {
          String fileDiscription="";
          File intputFile,outputFile;
         
          getFiles();
         
          if(cancelFlag!=JFileChooser.CANCEL_OPTION)
          {
               for(int knt=0;knt<selectedFiles.length;knt++)
               {
                    intputFile = new File(directory+"\\"+selectedFiles[knt]);          //sets the location of the input file

                         String outFile="xxxxxxxxxx";
                          while(outFile.length>8)
                       {
                               //outFile = get the file name from the user
                               //check that outFile endsWith .csv
                     }
                    outputFile = new File(home+outFile);                         //sets the location of the output file
                   
                    try
                    {    
                         copyFile(intputFile,outputFile,home);
               }
                    catch(IOException e)
                    {
                         JOptionPane.showMessageDialog(null,"Unable to upload "+selectedFiles[knt],"ERROR",JOptionPane.ERROR_MESSAGE);
                    }
               }
          }
     }
     
     /*******************************************************************************
     getFiles()
     
     This opens a JFileChooser and allows the user to browse their computer for files.
     *******************************************************************************/
     
     private void getFiles()
     {
          JFileChooser chooser = new JFileChooser();

          chooser.setAcceptAllFileFilterUsed(false);               //does not allow user to use the AllFiles type option.
          chooser.addChoosableFileFilter(new csvFilter());     //filters selection to only allow html and htm files
          chooser.setMultiSelectionEnabled(true);                //Allows the user to select multiple files

          try     //this sets the look and feel of the file chooser to the currently selected look and feel
          {
               UIManager.setLookAndFeel(UserMenu.looks[UserMenu.lookNumber].getClassName());
               SwingUtilities.updateComponentTreeUI(this);
          }
          catch(Exception e)
          {
               new ErrorLogger("Error getFiles() - fileLoader.java:    "+e);
          }
         
          cancelFlag = chooser.showOpenDialog(this);
         
          directory = (chooser.getCurrentDirectory()).toString();     //gets the current directory
         
          File tempFiles[] = chooser.getSelectedFiles();
         
          selectedFiles = new String[tempFiles.length];
         
          for(int knt=0;knt<tempFiles.length;knt++)
          {
               selectedFiles[knt] = tempFiles[knt].getName();
          }
     }

/*******************************************************************************
     copyFile(File, File, String)
     
     This method copies the input file to the selected output directory.
     *******************************************************************************/
     
     public void copyFile(File inputFile, File outputFile, String directory) throws IOException
     {
          if((new File(directory).mkdir()));           //creates home directory if needed
         
          InputStream inStream = new FileInputStream(inputFile);
          OutputStream outStream = new FileOutputStream(outputFile);
         
          byte[] buffer = new byte[1024];
          int length;
         
          while ((length = inStream.read(buffer)) > 0)
          {
               outStream.write(buffer, 0, length);
          }
         
          inStream.close();
          outStream.close();
     }

//Another Class to filter out the csv files

import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

public class csvFilter extends FileFilter
{
      /*******************************************************************************
      accept(File)
      
      This filters out files and only allows htm and html files to be selected
      *******************************************************************************/
      
      public boolean accept(File file)
      {
            if (file.isDirectory())
                  return true;

            String extension = getExtension(file);
            
            if (extension != null)
            {
                  if (extension.equals("csv")&&(file.toString()).length()>=14) //10+.csv
                        return true;
                  else
                        return false;
            }
            return false;
      }
      
      /*******************************************************************************
      getDescription()
      
      This returns the discription of the available files
      *******************************************************************************/
      
      public String getDescription()
      {
            return ".htm, .html";
      }
      
      /*******************************************************************************
      getExtension(File)
      
      This returns the extension of a file
      *******************************************************************************/
      
      private String getExtension(File file)
      {
                  String ext = null;
                  String name = file.getName();
                  int index = name.lastIndexOf('.'); //finds the index of the '.' thus any data after this is the extension
                  
                  if(index>0&&(index<name.length()-1))
                  {
                        ext = name.substring(index+1).toLowerCase(); //this gets the extension characters
                  }
                  
                  return ext;
      }
}

As for deleting the file go to this link for a simple example http://javaalmanac.com/egs/java.io/DeleteFile.html
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
What's wrong with this code? 4 36
java imports not found 4 51
maven not picking latest jar instead picking old jar from .m2 12 48
IBM TS2900 (3572) Tape Autoloader Java? 12 61
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question