LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 10-06-2004, 07:27 PM   #1
ludeKing
Member
 
Registered: Jul 2003
Location: NSW. Australia
Distribution: Ubuntu, Fedora, Slackware
Posts: 181

Rep: Reputation: 30
java - parent directory problem


Hi,
I am writing a program that gets two strings from the user input.

1. The source directory (ie where a bunch of files and or folders are located)
2. The destination directory (ie where the files should end up)

It then creates a mirror image of those files and folders in a different palce, but without actaully copying the files. ie a set of dummy files and folders with 0 size.

The problem I have is that when I try to create (firstly) a string representation of the final destination directory, by concatenating the two strings together (source and dest) I can't get it right.

I need a way to remove the initial parent directories from the path of the source directory location.

I know this sounds cofusing so here's my code for this method:
Code:
private void traverseAllDirsAndFiles(File drive) {
            
         if (drive.isDirectory()) {
            String[] children = drive.list();
            for (int i=0; i<children.length; i++) {
                traverseAllDirsAndFiles(new File(drive, children[i]));
                             
                
                //need to make a file object out of each entry we come across
                File traverse = new File(drive, children[i]);
                
                //THIS IS MY PROB - I CAN"T GET THE DESTINATION STRING RIGHT
                //System.err.println("full dest is: " + destination_path + File.separator + "CDROM" + File.separator + traverse.getName());
                
                //the rest isn't a problem..............

//now, if we come across a directory, make that directory in dest
                if (traverse.isDirectory()) {
                    System.out.println(traverse + " is directory");
                    //mkdir() later;
                    
                }
                //or, if we come across a file, make that file in the destination
                else if (traverse.isFile()) {
                    System.out.println(traverse + " is a normal file");
                    //createNewFile() later;
                    
                }
                
                else { 
                System.err.println("An error has occurred reading the directory you specified.");
                }
            }
            
         }
 
Old 10-06-2004, 11:47 PM   #2
dustu76
Member
 
Registered: Sep 2004
Distribution: OpenSuSe
Posts: 153

Rep: Reputation: 30
You should be having a header file "libgen.h" (may be in /usr/include) which should have a basename function.

That should give only the filename from the pathname.

HTH.
 
Old 10-07-2004, 02:21 AM   #3
ludeKing
Member
 
Registered: Jul 2003
Location: NSW. Australia
Distribution: Ubuntu, Fedora, Slackware
Posts: 181

Original Poster
Rep: Reputation: 30
Um, this is for Java, not C, sorry. I'm still having probs if anyone else has an idea.
 
Old 10-07-2004, 02:31 AM   #4
jlliagre
Moderator
 
Registered: Feb 2004
Location: Outside Paris
Distribution: Solaris 11.4, Oracle Linux, Mint, Ubuntu/WSL
Posts: 9,785

Rep: Reputation: 492Reputation: 492Reputation: 492Reputation: 492Reputation: 492
Can you better describe the problem you are facing, with a concrete example, the expected result and error messages ?
 
Old 10-07-2004, 08:27 AM   #5
ludeKing
Member
 
Registered: Jul 2003
Location: NSW. Australia
Distribution: Ubuntu, Fedora, Slackware
Posts: 181

Original Poster
Rep: Reputation: 30
Yep.
Basically, the user is prompted for two pieces of input.

1 the source directory which can be any directory containing any number of files and or folders etc.
2. the destination directory

What will happen, is when the 2nd piece of info is received (destination directory), then a mirror image of those files and folders from the source directory will be created in the destination directory, but with zero size. Think of it as copying a folder from one spot to the next, but haveing all the files end up with zero size.

The point of this is that on a site for uni, lecturers can link from online, to a cd that is in the students local cd drive. To do this, the tool requires a bunch of dummy files be made up, so that you actually link those dummy files, but the data feed come from the cd on the drive itself (which the studentssets up by entering the path of teh cdrom).... then when the students click on the links to the files that the lecturer has posted, the data is accessed from thecd instead of the server....

SO.... this app simply creates those dummy files easily and quickly.

So in the code, what I need it to do, is open the source directory and read its contents and traverse through all the files and folders in that source directory. At the moment I am just trying to get the string representation of wher ethe files and folders are at, but the folder portion is lost and just the filename appears, which is bad because there are files inside some folders.

here is the entire class code (slightly diff to first post as I've been playing):
Code:
/*
 * CDRom_App.java
 *
 * 
 */

package une.webct.cdrom_app;

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

/**
 *
 * @author  Stephen Swinsburg
 * @date    06/10/04
 *
 */
public class CDRom_App extends javax.swing.JFrame {
    
    /** Creates new form CDRom_App */
    public CDRom_App() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        text_1 = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        path_text = new javax.swing.JLabel();
        path_field = new javax.swing.JTextField();
        browse_1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        dest_text = new javax.swing.JLabel();
        dest_path = new javax.swing.JTextField();
        browse_2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        go = new javax.swing.JButton();
        progress = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        quit = new javax.swing.JButton();

        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        text_1.setBackground(new java.awt.Color(236, 233, 216));
        text_1.setEditable(false);
        text_1.setText("The WebCT CDROM Helper Utility.\n\n1. Insert your course CD into your CD Drive\n2. Click 'Browse1' to choose the path of your CDROM drive.\n3. Click 'Browse2' to select where you want the generated files to be stored .\n3. Click 'Go' to generate the files and folders to upload.\n\n");
        text_1.setMaximumSize(new java.awt.Dimension(500, 110));
        text_1.setMinimumSize(new java.awt.Dimension(500, 110));
        text_1.setOpaque(false);
        text_1.setPreferredSize(new java.awt.Dimension(500, 110));
        getContentPane().add(text_1);

        jPanel1.setForeground(new java.awt.Color(236, 233, 216));
        jPanel1.setMaximumSize(new java.awt.Dimension(500, 50));
        jPanel1.setMinimumSize(new java.awt.Dimension(500, 50));
        jPanel1.setPreferredSize(new java.awt.Dimension(500, 50));
        path_text.setText("Path to CD e.g. D:\\");
            path_text.setFocusable(false);
            jPanel1.add(path_text);

            path_field.setMaximumSize(new java.awt.Dimension(150, 20));
            path_field.setMinimumSize(new java.awt.Dimension(150, 20));
            path_field.setPreferredSize(new java.awt.Dimension(150, 20));
            jPanel1.add(path_field);

            browse_1.setText("Browse1");
            browse_1.setMaximumSize(new java.awt.Dimension(90, 25));
            browse_1.setMinimumSize(new java.awt.Dimension(90, 25));
            browse_1.setPreferredSize(new java.awt.Dimension(90, 25));
            browse_1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    browse_1ActionPerformed(evt);
                }
            });

            jPanel1.add(browse_1);

            getContentPane().add(jPanel1);

            jPanel2.setForeground(new java.awt.Color(236, 233, 216));
            jPanel2.setMaximumSize(new java.awt.Dimension(500, 50));
            jPanel2.setMinimumSize(new java.awt.Dimension(500, 50));
            jPanel2.setPreferredSize(new java.awt.Dimension(500, 50));
            dest_text.setText("Destination Path:");
            dest_text.setEnabled(false);
            dest_text.setFocusable(false);
            jPanel2.add(dest_text);

            dest_path.setEnabled(false);
            dest_path.setMaximumSize(new java.awt.Dimension(200, 20));
            dest_path.setMinimumSize(new java.awt.Dimension(200, 20));
            dest_path.setPreferredSize(new java.awt.Dimension(200, 20));
            jPanel2.add(dest_path);

            browse_2.setText("Browse2");
            browse_2.setEnabled(false);
            browse_2.setMaximumSize(new java.awt.Dimension(90, 25));
            browse_2.setMinimumSize(new java.awt.Dimension(90, 25));
            browse_2.setPreferredSize(new java.awt.Dimension(90, 25));
            browse_2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    browse_2ActionPerformed(evt);
                }
            });

            jPanel2.add(browse_2);

            getContentPane().add(jPanel2);

            jPanel3.setForeground(new java.awt.Color(236, 233, 216));
            jPanel3.setMaximumSize(new java.awt.Dimension(500, 50));
            jPanel3.setMinimumSize(new java.awt.Dimension(500, 50));
            jPanel3.setPreferredSize(new java.awt.Dimension(500, 50));
            go.setText("Go!");
            go.setEnabled(false);
            go.setMaximumSize(new java.awt.Dimension(100, 25));
            go.setMinimumSize(new java.awt.Dimension(100, 25));
            go.setPreferredSize(new java.awt.Dimension(80, 25));
            go.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    goActionPerformed(evt);
                }
            });

            jPanel3.add(go);

            getContentPane().add(jPanel3);

            progress.setBackground(new java.awt.Color(236, 233, 216));
            progress.setEditable(false);
            progress.setMaximumSize(new java.awt.Dimension(500, 150));
            progress.setMinimumSize(new java.awt.Dimension(500, 150));
            progress.setOpaque(false);
            progress.setPreferredSize(new java.awt.Dimension(500, 150));
            getContentPane().add(progress);

            jPanel4.setForeground(new java.awt.Color(236, 233, 216));
            jPanel4.setMaximumSize(new java.awt.Dimension(500, 50));
            jPanel4.setMinimumSize(new java.awt.Dimension(500, 50));
            jPanel4.setPreferredSize(new java.awt.Dimension(500, 50));
            quit.setText("Finish");
            quit.setEnabled(false);
            quit.setMaximumSize(new java.awt.Dimension(100, 25));
            quit.setMinimumSize(new java.awt.Dimension(100, 25));
            quit.setPreferredSize(new java.awt.Dimension(80, 25));
            quit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quitActionPerformed(evt);
                }
            });

            jPanel4.add(quit);

            getContentPane().add(jPanel4);

            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-500)/2, (screenSize.height-500)/2, 500, 500);
        }//GEN-END:initComponents

    private void quitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitActionPerformed
        
        //done, so quit.
        System.exit(0);
    }//GEN-LAST:event_quitActionPerformed

    private void goActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goActionPerformed
        
        //we want to traverse all directories, subdirecotries and files
        //and do stuff with them
        //create a file object and pass it to the method that will do this
        File drive = new File(path_to_drive);
        
        //call the method to go through the entire directory structure
        traverseAllDirsAndFiles(drive, destination_path);
               
        
    }//GEN-LAST:event_goActionPerformed

    private void browse_2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browse_2ActionPerformed
        
        //we want this to open in a new frame
        JFrame frame2 = new JFrame();
        
        JFileChooser chooser2 = new JFileChooser();
        
        chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int returnVal = chooser2.showOpenDialog(frame2);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose destination directory of: " +
            chooser2.getSelectedFile());
        
        //update the path_field textbox
        destination_path = chooser2.getSelectedFile().toString();
        dest_path.setText(destination_path);

        //enable the next few options
        go.setEnabled(true);
        
        } 
        
        
    }//GEN-LAST:event_browse_2ActionPerformed

    private void browse_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browse_1ActionPerformed
        
        //we want this to open in a new frame
        JFrame frame = new JFrame();
        
        JFileChooser chooser = new JFileChooser();
        
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int returnVal = chooser.showOpenDialog(frame);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose source directory of: " +
            chooser.getSelectedFile());
        
        //update the path_field textbox
        path_to_drive = chooser.getSelectedFile().toString();
        path_field.setText(path_to_drive);

        //enable the next few options
        dest_text.setEnabled(true);
        dest_path.setEnabled(true);
        browse_2.setEnabled(true);
        
    }

    }//GEN-LAST:event_browse_1ActionPerformed
    
    //************* HERES THE METHOD ***************


// Process all files and directories under 'drive'
    private void traverseAllDirsAndFiles(File drive, String destination_path) {
            
           // my logic:
           // for each file in the directory:
           // if the file is a directory:
           // Print its contents recursively
           // else
           // Print the name of the file.
         
           
          String[] files;  // List of names of files in the directory.
          //System.out.println("dest is " + destination_path + File.separator + drive.getName());
          
          files = drive.list();
          for (int i = 0; i < files.length; i++) {
                   // If the file is a  directory, list its contents
                   // recursively.  Otherwise, just print its name.
              File f = new File(drive, files[i]);
              
              //parse files first - but how - so as to stop any unnessecary concat of extra dir names
              
              if (f.isFile()) {
                  System.out.println(destination_path + File.separator + files[i]);
                  //create the file now
              
              } 
              if (f.isDirectory()) {
                 
                 //now recurse and do the rest and keep descending into dirs.
                 traverseAllDirsAndFiles(f, destination_path);
                 
                 //add the dirname to the destination path
                 destination_path = destination_path + File.separator + f.getName();
                 //create the file now
               
              } else {
                  System.err.println("An error occurred reading the directories.");
                 
              }
          }
           
        quit.setEnabled(true);
    }
    
    
     
    
    
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CDRom_App().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browse_1;
    private javax.swing.JButton browse_2;
    private javax.swing.JTextField dest_path;
    private javax.swing.JLabel dest_text;
    private javax.swing.JButton go;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JTextField path_field;
    private javax.swing.JLabel path_text;
    private javax.swing.JTextArea progress;
    private javax.swing.JButton quit;
    private javax.swing.JTextArea text_1;
    // End of variables declaration//GEN-END:variables
    
    String path_to_drive;
    String destination_path;
    
    
}
compile it and run it and you can see what happens in the stderr stream.

Any ideas? Thanks.

Last edited by ludeKing; 10-07-2004 at 08:29 AM.
 
Old 10-07-2004, 12:29 PM   #6
jlliagre
Moderator
 
Registered: Feb 2004
Location: Outside Paris
Distribution: Solaris 11.4, Oracle Linux, Mint, Ubuntu/WSL
Posts: 9,785

Rep: Reputation: 492Reputation: 492Reputation: 492Reputation: 492Reputation: 492
Quote:
you can see what happens in the stderr stream.
I would prefer you to post your stderr output ... Well, I compiled the beast, and I got a "An error occurred reading the directories." error message.
Is this the problem you have ?

Sorry if I was unclear, but I was trying to have you narrowing your problem to something clear and isolated, but it had the opposite effect ...

Nevermind, it looks like the issue is:
Quote:
the folder portion is lost and just the filename appears
Can you show us what you expect, with what objets and methods and what you got instead ?
 
Old 10-07-2004, 06:31 PM   #7
ludeKing
Member
 
Registered: Jul 2003
Location: NSW. Australia
Distribution: Ubuntu, Fedora, Slackware
Posts: 181

Original Poster
Rep: Reputation: 30
Ok here we go:


output
Code:
You chose source directory of: C:\Documents and Settings\sswinsb2\Desktop\testing
You chose destination directory of: C:\Documents and Settings\sswinsb2\My Documents
\folder1
\folder1\folder1_1
\folder1\folder1_1\text1_1.txt
\folder1\folder1_1\text1.txt
\folder1\folder2
\folder1\folder2\text2.txt
\folder1\folder2\text.txt
Sorry I am at work and had to use Windoze!
This is almost right except the file structure of the source directory is:

Code:
testing (top level dir)
        |
        |
        |---folder1 (subdir)
        |       |
        |       |---folder1_1 (subdir of folder1)
        |       |       |     
        |       |       |---text1_1.txt (file in folder 1_1)
        |       |
        |       |---text1.txt (file in folder1 dir)
        |
        |---folder2 (subdir)
        |       |
        |       |--text2.txt (file in folder2 dir)
        |
        |
        |---text.txt (file in topmost level dir)

and that is with a slightly rewritten method... the whole new class is below (works this time)
Code:
/*
 * CDRom_App.java
 *
 * 
 */

package une.webct.cdrom_app;

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

/**
 *
 * @author  Stephen Swinsburg
 * @date    06/10/04
 *
 */
public class CDRom_App extends javax.swing.JFrame {
    
    /** Creates new form CDRom_App */
    public CDRom_App() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {                          
        text_1 = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        path_text = new javax.swing.JLabel();
        path_field = new javax.swing.JTextField();
        browse_1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        dest_text = new javax.swing.JLabel();
        dest_path = new javax.swing.JTextField();
        browse_2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        go = new javax.swing.JButton();
        progress = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        quit = new javax.swing.JButton();

        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        text_1.setBackground(new java.awt.Color(236, 233, 216));
        text_1.setEditable(false);
        text_1.setText("The WebCT CDROM Helper Utility.\n\n1. Insert your course CD into your CD Drive\n2. Click 'Browse1' to choose the path of your CDROM drive.\n3. Click 'Browse2' to select where you want the generated files to be stored .\n3. Click 'Go' to generate the files and folders to upload.\n\n");
        text_1.setMaximumSize(new java.awt.Dimension(500, 110));
        text_1.setMinimumSize(new java.awt.Dimension(500, 110));
        text_1.setOpaque(false);
        text_1.setPreferredSize(new java.awt.Dimension(500, 110));
        getContentPane().add(text_1);

        jPanel1.setForeground(new java.awt.Color(236, 233, 216));
        jPanel1.setMaximumSize(new java.awt.Dimension(500, 50));
        jPanel1.setMinimumSize(new java.awt.Dimension(500, 50));
        jPanel1.setPreferredSize(new java.awt.Dimension(500, 50));
        path_text.setText("Path to CD e.g. D:\\");
            path_text.setFocusable(false);
            jPanel1.add(path_text);

            path_field.setMaximumSize(new java.awt.Dimension(150, 20));
            path_field.setMinimumSize(new java.awt.Dimension(150, 20));
            path_field.setPreferredSize(new java.awt.Dimension(150, 20));
            jPanel1.add(path_field);

            browse_1.setText("Browse1");
            browse_1.setMaximumSize(new java.awt.Dimension(90, 25));
            browse_1.setMinimumSize(new java.awt.Dimension(90, 25));
            browse_1.setPreferredSize(new java.awt.Dimension(90, 25));
            browse_1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    browse_1ActionPerformed(evt);
                }
            });

            jPanel1.add(browse_1);

            getContentPane().add(jPanel1);

            jPanel2.setForeground(new java.awt.Color(236, 233, 216));
            jPanel2.setMaximumSize(new java.awt.Dimension(500, 50));
            jPanel2.setMinimumSize(new java.awt.Dimension(500, 50));
            jPanel2.setPreferredSize(new java.awt.Dimension(500, 50));
            dest_text.setText("Destination Path:");
            dest_text.setEnabled(false);
            dest_text.setFocusable(false);
            jPanel2.add(dest_text);

            dest_path.setEnabled(false);
            dest_path.setMaximumSize(new java.awt.Dimension(200, 20));
            dest_path.setMinimumSize(new java.awt.Dimension(200, 20));
            dest_path.setPreferredSize(new java.awt.Dimension(200, 20));
            jPanel2.add(dest_path);

            browse_2.setText("Browse2");
            browse_2.setEnabled(false);
            browse_2.setMaximumSize(new java.awt.Dimension(90, 25));
            browse_2.setMinimumSize(new java.awt.Dimension(90, 25));
            browse_2.setPreferredSize(new java.awt.Dimension(90, 25));
            browse_2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    browse_2ActionPerformed(evt);
                }
            });

            jPanel2.add(browse_2);

            getContentPane().add(jPanel2);

            jPanel3.setForeground(new java.awt.Color(236, 233, 216));
            jPanel3.setMaximumSize(new java.awt.Dimension(500, 50));
            jPanel3.setMinimumSize(new java.awt.Dimension(500, 50));
            jPanel3.setPreferredSize(new java.awt.Dimension(500, 50));
            go.setText("Go!");
            go.setEnabled(false);
            go.setMaximumSize(new java.awt.Dimension(100, 25));
            go.setMinimumSize(new java.awt.Dimension(100, 25));
            go.setPreferredSize(new java.awt.Dimension(80, 25));
            go.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    goActionPerformed(evt);
                }
            });

            jPanel3.add(go);

            getContentPane().add(jPanel3);

            progress.setBackground(new java.awt.Color(236, 233, 216));
            progress.setEditable(false);
            progress.setMaximumSize(new java.awt.Dimension(500, 150));
            progress.setMinimumSize(new java.awt.Dimension(500, 150));
            progress.setOpaque(false);
            progress.setPreferredSize(new java.awt.Dimension(500, 150));
            getContentPane().add(progress);

            jPanel4.setForeground(new java.awt.Color(236, 233, 216));
            jPanel4.setMaximumSize(new java.awt.Dimension(500, 50));
            jPanel4.setMinimumSize(new java.awt.Dimension(500, 50));
            jPanel4.setPreferredSize(new java.awt.Dimension(500, 50));
            quit.setText("Finish");
            quit.setEnabled(false);
            quit.setMaximumSize(new java.awt.Dimension(100, 25));
            quit.setMinimumSize(new java.awt.Dimension(100, 25));
            quit.setPreferredSize(new java.awt.Dimension(80, 25));
            quit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quitActionPerformed(evt);
                }
            });

            jPanel4.add(quit);

            getContentPane().add(jPanel4);

            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-500)/2, (screenSize.height-500)/2, 500, 500);
        }                        

    private void quitActionPerformed(java.awt.event.ActionEvent evt) {                                     
        
        //done, so quit.
        System.exit(0);
    }                                    

    private void goActionPerformed(java.awt.event.ActionEvent evt) {                                   
        
        //we want to traverse all directories, subdirecotries and files
        //and do stuff with them
        //create a file object and pass it to the method that will do this
        File drive = new File(path_to_drive);
        
        //call the method to go through the entire directory structure
        traverseAllDirsAndFiles(drive, file_structure);
               
        
    }                                  

    private void browse_2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        //we want this to open in a new frame
        JFrame frame2 = new JFrame();
        
        JFileChooser chooser2 = new JFileChooser();
        
        chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int returnVal = chooser2.showOpenDialog(frame2);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose destination directory of: " +
            chooser2.getSelectedFile());
        
        //update the path_field textbox
        destination_path = chooser2.getSelectedFile().toString();
        dest_path.setText(destination_path);

        //enable the next few options
        go.setEnabled(true);
        
        } 
        
        
    }                                        

    private void browse_1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
        //we want this to open in a new frame
        JFrame frame = new JFrame();
        
        JFileChooser chooser = new JFileChooser();
        
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        int returnVal = chooser.showOpenDialog(frame);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose source directory of: " +
            chooser.getSelectedFile());
        
        //update the path_field textbox
        path_to_drive = chooser.getSelectedFile().toString();
        path_field.setText(path_to_drive);

        //enable the next few options
        dest_text.setEnabled(true);
        dest_path.setEnabled(true);
        browse_2.setEnabled(true);
        
    }

    }                                        
    
   // Process all files and directories under 'drive'
    private void traverseAllDirsAndFiles(File drive, String file_structure) {
            
           // Print the name of the directory
           // for each file in the directory:
           // if the file is a directory:
           // Print its contents recursively
           // else
           // Print the name of the file.
           
              // Assume that dir is a directory.  List
              // its contents, including the contents of
              // subdirectories at all levels.
           
           String[] files;  // The names of the files in the directory.
           files = drive.list();
           for (int i = 0; i < files.length; i++) {
               File f;  // One of the files in the directory.
               f = new File(drive, files[i]);
               if ( f.isDirectory() ) {
                      // Call listContents() recursively to
                      // list the contents of the directory, f.
                   file_structure += File.separator + f.getName();
                   System.out.println(file_structure);
                   traverseAllDirsAndFiles(f, file_structure);
               }
               else {
                     // For a regular file, just print the name, files[i].
                   file_structure += File.separator + f.getName();
                   System.out.println(file_structure);
                   
                      }
                      
           }
           
      

    
        quit.setEnabled(true);
    }
    
     
    
    
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CDRom_App().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton browse_1;
    private javax.swing.JButton browse_2;
    private javax.swing.JTextField dest_path;
    private javax.swing.JLabel dest_text;
    private javax.swing.JButton go;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JTextField path_field;
    private javax.swing.JLabel path_text;
    private javax.swing.JTextArea progress;
    private javax.swing.JButton quit;
    private javax.swing.JTextArea text_1;
    // End of variables declaration                   
    
    String path_to_drive;
    String destination_path;
    String file_structure = "";
} 
    
    
/**
 *  file structure of the example folder I'm using
 *
 *
    testing (top level dir)
        |
        |
        |---folder1 (subdir)
        |       |
        |       |---folder1_1 (subdir of folder1)
        |       |       |     
        |       |       |---text1_1.txt (file in folder 1_1)
        |       |
        |       |---text1.txt (file in folder1 dir)
        |
        |---folder2 (subdir)
        |       |
        |       |--text2.txt (file in folder2 dir)
        |
        |
        |---text.txt (file in topmost level dir)
    **/

Last edited by ludeKing; 10-07-2004 at 08:09 PM.
 
Old 10-07-2004, 06:45 PM   #8
ludeKing
Member
 
Registered: Jul 2003
Location: NSW. Australia
Distribution: Ubuntu, Fedora, Slackware
Posts: 181

Original Poster
Rep: Reputation: 30
what i think I really need ts to be able to force te method to process ALL the files (and olny files) in a particular directory first, the each directory... this will save the unwated concatenation of dirnames...... how could I do this?

EDIT: I've got it! A sort! I need to sort the array of files so that all the files are first and are processed first! I think that would do it!

Last edited by ludeKing; 10-07-2004 at 06:55 PM.
 
Old 10-07-2004, 07:25 PM   #9
ludeKing
Member
 
Registered: Jul 2003
Location: NSW. Australia
Distribution: Ubuntu, Fedora, Slackware
Posts: 181

Original Poster
Rep: Reputation: 30
ok i found a method that sorts file objects by directories first so I modified it to make it files first....
http://leepoint.net/notes-java/25dat...70sorting.html

this is the original class which works great - as a standalone class

Code:
// arrays/-filelist/Filelistsort.java - List contents of directory.
// Takes directory name as command line parameter.
// Fred Swartz - 2003-09-15

import java.util.Arrays;
import java.util.Comparator;
import java.io.*;

public class Filelistsort {
    public static void main(String[] args) {
        File dir = new File(args[0]);
        
        File[] children = dir.listFiles();

        Arrays.sort(children, new Comparator() {
            public int compare(Object a, Object b) {
                File filea = (File)a;
                File fileb = (File)b;
                //--- Sort directories before files, 
                //    otherwise alphabetical ignoring case.
                if (filea.isDirectory() && !fileb.isDirectory()) {
                    return -1;
                } else if (!filea.isDirectory() && fileb.isDirectory()) {
                    return 1;
                } else {
                    return filea.getName().compareToIgnoreCase(fileb.getName());
                }
            }
        });
        
        for (int i=0; i<children.length; i++) {
            System.out.println(children[i].getName());
        }
    }
}

and now my code which incorporates this sorting work:
Code:
 
   // Process all files and directories under 'drive'
    private void traverseAllDirsAndFiles(File drive, String file_structure) {
            
           // Print the name of the directory
           // for each file in the directory:
           // if the file is a directory:
           // Print its contents recursively
           // else
           // Print the name of the file.
           
           String[] files = drive.list();  // The names of the files in the directory.
           
           //really need to force it so that we only process the files first.
           //a sort! sort the files first so they are processed first! Yes!
           Arrays.sort(files, new Comparator() {
             public int compare(Object a, Object b) {
                File filea = (File)a;
                File fileb = (File)b;
                
                //--- Sort files before directories, 
                //    otherwise alphabetical ignoring case.
                if (filea.isFile() && !fileb.isFile()) {
                    return -1;
                } else if (!filea.isFile() && fileb.isFile()) {
                    return 1;
                } else {
                    return filea.getName().compareToIgnoreCase(fileb.getName());
                }
            }
          });
        
           //now we process each file object, as they are in the order we want
           for (int i = 0; i < files.length; i++) {
                         
               File f = new File(drive, files[i]);// One of the file objects in the directory.
            
               if ( f.isDirectory() ) {
                   // Call traverse() recursively to go through the directory which
                   // it cats, prints then passes to the traverse method
                   file_structure += File.separator + f.getName();
                   System.out.println(file_structure);
                   traverseAllDirsAndFiles(f, file_structure);
               }
                             
               else {
                   // For a regular file, just make the path and print the name.
                   file_structure += File.separator + f.getName();
                   System.out.println(file_structure);
                   
               }
                    
           }
 
      
        //enable the finish button
        finish.setEnabled(true);
    }
and I get a classCastException! argh! the one above works good!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to check if a parent directory is a symbolic link compnovice Linux - Newbie 11 10-06-2005 05:59 PM
.htaccess restricting parent directory Braytac Linux - Networking 2 05-26-2005 05:27 PM
'cp -rv .*' recurses into the parent directory??? stefanlasiewski SUSE / openSUSE 5 02-02-2005 05:36 PM
List only the parent directory scottrell Linux - General 6 11-07-2003 09:10 AM
mv the contents of one directory to the parent directory warkrime Linux - Newbie 4 07-14-2003 07:03 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:12 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration