Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Reading Directories and Files in Java

Posted on 2004-08-10
7
Medium Priority
?
650 Views
Last Modified: 2012-08-14
I have a combo box control in Java with a first element of "NEW". When i pull down the combo box menu it should display the files  listed in a directory under windows. I should be able to open the file that I select and display the contents to a List Box. If I select "NEW" it should clear the contents of the List Box.

I need some code samples that I can try, which is the reason for the high points. If you've done this before or know where to get some code samples please provide information and I will award the points.

thanks
GS
0
Comment
Question by:GoldStrike
[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
  • 4
7 Comments
 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 2000 total points
ID: 11765262
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11765630
the following code may helps you to write your further code

import javax.swing.*;
import java.io.*;
/*
 * Created on Aug 10, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Sudhakar
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class AddFiles extends JFrame {
      
      JComboBox combo=new JComboBox();
      public AddFiles()
      {
            init();
      }
      public void init()
      {
            addFiles(combo,"c:/");
            JPanel pane=new JPanel();
            pane.add(combo);
            this.getContentPane().add(pane);
      }
      public static void main(String s[])
      {
            AddFiles files=new AddFiles();
            files.setSize( 400,300);
            files.show() ;
      }
      public void addFiles(JComboBox _combo,String file)
      {
            File dir = new File(file);
          
          String[] children = dir.list();
          if (children == null) {
              // Either dir does not exist or is not a directory
          } else {
              for (int i=0; i<children.length; i++) {
                  // Get filename of file or directory
                  String filename = children[i];
                  _combo.addItem(filename );
              }
          }

      }

}
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11766035
and this is ur combo listener class
class MyActionListener implements ActionListener {
                public void actionPerformed(ActionEvent ae)
      {       
                      if(ae.getSource() ==combo)
             {
                   JComboBox cb = (JComboBox)ae.getSource();
                   Object newItem = cb.getSelectedItem();
                   try
                  {
                         FileInputStream fin=new FileInputStream(newItem.toString());
                         File file=new File(newItem.toString());
                         int length=(int)file.length();
                         byte bytes[]=new byte[length];
                         fin.read(bytes);
                         String string=new String(bytes);
                         String[] lines=string.split( "\n");
                         for(int i=0;i<lines.length;i++)
                         {
                               list.add(lines[i],null);
                               System.err.println(lines[i]);
                         }
                         
                  }
                   catch(Exception ex)
                  {
                               
                     }
             }
       }
0
Independent Software Vendors: 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!

 
LVL 1

Expert Comment

by:jmeree
ID: 11768425
Why not use a JFileChooser like this? (created with netbeans)

import java.io.BufferedReader;
import javax.swing.JFileChooser;

public class FileViewer extends javax.swing.JFrame {
   
    private javax.swing.JButton exitButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JButton newButton;
    private javax.swing.JButton openButton;
   
    public FileViewer() {
        super("File Viewer");
        initComponents();
    }
   
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        openButton = new javax.swing.JButton();
        newButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });

        jTextArea1.setPreferredSize(new java.awt.Dimension(300, 300));
        jScrollPane1.setViewportView(jTextArea1);

        jPanel1.add(jScrollPane1);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH);

        openButton.setLabel("Open");
        openButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                openButtonMouseClicked(evt);
            }
        });

        jPanel3.add(openButton);

        newButton.setLabel("New");
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });
        jPanel3.add(newButton);

        exitButton.setLabel("Exit");
        exitButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exitButtonMouseClicked(evt);
            }
        });

        jPanel3.add(exitButton);

        getContentPane().add(jPanel3, java.awt.BorderLayout.SOUTH);

        pack();
    }

    private void exitButtonMouseClicked(java.awt.event.MouseEvent evt) {
        System.exit (0) ;
    }

    private void openButtonMouseClicked(java.awt.event.MouseEvent evt) {
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
           java.io.File f = chooser.getSelectedFile();
           System.out.println("You chose to open this file: " + f.getAbsolutePath() );
           try {
               BufferedReader br = new BufferedReader ( new java.io.FileReader(f) );
               String tempLine = null ;
               jTextArea1.setText(null);
               while( ( tempLine = br.readLine() ) != null ) { jTextArea1.append( tempLine + "\n" );  }
           }
           catch ( java.io.FileNotFoundException e ) {
              e.printStackTrace();
              System.exit (-1);
           }
           catch ( java.io.IOException e ) {
              e.printStackTrace();
              System.exit (-1);
           }
        }
    }

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {
        jTextArea1.setText(null);
    }
   
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
   
    public static void main(String args[]) {
        new FileViewer().show();
    }
   
}
0
 

Author Comment

by:GoldStrike
ID: 11882016
thanks for all the inputs, I apologize for being late. The GetFiles and Add Items answered my questions.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11883700
:-)
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses

636 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