0

I'm trying to build a GUI that uses a JFileChooser to select a file and store the name of the file in a String[] array. I can't for the life of me get it to work. It keeps throwing the IllegalArgumentException: filenames array needs two filenames in it. Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: filenames array needs two filenames in it.

I have a diff class:

package diff.model;
import java.io.*;

/**
* Determines the difference between two text files on a line-by-line basis.
* Usage: see println's in main method.
* 
*/
public class Diff {
// Data members
private static boolean outputToFile;
private static String outputFile;
private static String[] text = new String[]{null};
public static String file1, file2, outputfile;
public static String[] filenames = new String[]{file1, file2, outputfile};

/**
 * Constructor for objects of class Diff
 */
public Diff() {
    outputToFile = false;
}

/**
 * Checks if a file exists or not.
 * <p>
 * Precondition: A non-null string is passed in.
 * 
 * @param filename
 *            The filename to see if it exists or not.
 * @return true If the file exists and false otherwise.
 */
public boolean fileExists(String filename) {
    // Check precondition
    if (filename == null) {
        throw new IllegalArgumentException("filename is null.");
    }

    File file = new File(filename);

    return file.exists();

} 

/**
 * Compares two text files line-by-line, displaying any lines that differ.
 * <p>
 * Precondition: The array has two filenames for the files to
 * compare and three filenames if the output is also to go to a file.
 * 
 * @param filenames
 *            Array that contains the filenames
 */
public static void compareFiles(String[] filenames) {

    // Check preconditions
    if (filenames.length != 2 && outputToFile==false  ) {
        throw new IllegalArgumentException("filenames array needs two      filenames in it.");
    }
    else if (filenames.length != 3 && outputToFile==true){
        throw new IllegalArgumentException("filenames array needs three filenames in it.");
    }

    // Open the two input files
    try {
        // Open the two input files
        BufferedReader fin1 = new BufferedReader(new FileReader(
                filenames[0]));
        BufferedReader fin2 = new BufferedReader(new FileReader(
                filenames[1]));

        // Set up some local variables to be used when reading in the files
        String line1;
        String line2;
        int nCount = 0;
        boolean bContinue = true;
        boolean bDifference = false;

        // Loop reading in from each file comparing line-by-line
        while (bContinue) {
            line1 = fin1.readLine();
            line2 = fin2.readLine();

            // Make sure successfully read a line from each file
            if (line1 != null && line2 != null) {
                // Update the counter that keeps track of the number of
                // lines read
                nCount++;

                // See if the two lines differ
                if (!line1.equals(line2)) {
                    // The lines differ so set the flag that indicates the
                    // files are not identical
                    bDifference = true;

                    // Set the string to output and output the text
                    String[] text = { nCount + ": " + line1,
                            nCount + ": " + line2 };
                    outputText(text);

                } // end if (!line1.equals(line2))
            } // end if (line1 != null && line2 != null)
                // See if have reached the end of both files
            else if (line1 == null && line2 == null) {
                // Set the looping flag to false since reached the end of
                // both files
                bContinue = false;

                // See if files are completely identical, if they are then
                // output that they are identical
                if (!bDifference) {
                    // Set the string to output and output the text
                    String[] text = { filenames[0] + " and " + filenames[1]
                            + " are identical." };
                    outputText(text);
                }
            } else // Reached the end of one of the files
            {
                // Increment the line counter
                nCount++;
                int nStart = nCount; // Keep track of what line currently at

                // Set that the files are different
                bDifference = true;

                // Determine which file reached the end of
                if (line1 == null) {
                    // Count the number of remaining lines in file 2
                    nCount += determineRemainingLines(fin2);

                    // Set the string to output and output the text
                    String[] text = { "Lines " + nStart + " - " + nCount
                            + " only exist in " + filenames[1] };
                    outputText(text);
                } else {
                    // Count the number of remaining lines in file 1
                    nCount += determineRemainingLines(fin1);

                    // Set the string to output and output the text
                    String[] text = { "Lines " + nStart + " - " + nCount
                            + " only exist in " + filenames[0] };
                    outputText(text);
                }

            } 

        } 

        // Close the files
        fin1.close();
        fin2.close();

    } // end try
    catch (FileNotFoundException fnfx) {
        // Should not technically ever get here, because of earlier file
        // exists check but will have this code as a safety valve.
        System.out
                .println("Error: Input file was not found. Exiting program.");
    } catch (IOException iox) {
        System.err.println(iox.getMessage());
        iox.printStackTrace();
    }

} 

/**
 * Output the passed in text to the screen
 * <p>
 * Precondition: text is not null.
 * 
 * @param text
 *            [] An array of strings to print out. Each array item is
 *            printed on a single line.
 * 
 */
public static void outputText(String[] text) {
    // Check precondition
    if (text == null) {
        throw new IllegalArgumentException("text is null");
    }

    // Loop through element in the string array and print out each text
    // string in the array
    for (int i = 0; i < text.length; i++) {
        System.out.println(text[i]);

    } 

    // See if need to output the text to a file also
    if (outputToFile) {
        try {
            // Open a file to append to
            PrintWriter fileout = new PrintWriter(new BufferedWriter(
                    new FileWriter(outputFile, true)));

            // Loop through the array print out each array element to a
            // single line
            for (int i = 0; i < text.length; i++) {
                fileout.println(text[i]);

            } // end for

            fileout.close();

        } // end try
        catch (IOException iox) {
            System.err.println(iox.getMessage());
            iox.printStackTrace();
        }

    } 
} 

/**
 * Count the number of remaining lines in the open file.
 * <p>
 * Precondition: The file is pointing to an open file.
 * 
 * @param file
 *            File to continue counting lines in
 * @return The number of lines from the current point in the file to the end
 *         of the file.
 */
private static int determineRemainingLines(BufferedReader file) {
    if (file == null) {
        throw new IllegalArgumentException("file pointer is null.");
    }

    int nCount = 0;
    try {
        // Continue reading until end of file counting lines
        String line = file.readLine();
        while (line != null) {
            line = file.readLine();
            nCount++;

        }
    } 
    catch (IOException iox) {
        System.err.println(iox.getMessage());
        iox.printStackTrace();
    }

    return nCount;

}

/**
 * @return the filenames
 */
public static String[] getFilenames() {
    return filenames;
}

/**
 * @param filenames the filenames to set
 */
public static void setFilenames(String[] filenames) {
    Diff.filenames = filenames;
}
} 

And a DiffGUI class:

import diff.model.Diff;
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.text.*;
import java.util.Arrays;
import java.util.Scanner;

import java.awt.Color;
import java.io.*;

import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

public class DiffGUI extends JFrame {

private JPanel contentPane;
private final JButton btnFile01 = new JButton("Select File 1");
private final JButton btnFile02 = new JButton("Select File 2");
private final JTextField textField = new JTextField();
private final JTextField textField_1 = new JTextField();
private final JLabel lblFile = new JLabel("File 1:");
private final JLabel lblFile_1 = new JLabel("File 2:");
private final JButton btnCompareFiles = new JButton("Compare Files");
private final JLabel lblOutputFile = new JLabel("Output File:");
private final JTextField textField_2 = new JTextField();
private final JTextArea textArea = new JTextArea();

private String[] filenames;

// Create a new diff object
Diff differ = new Diff();

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                DiffGUI frame = new DiffGUI();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public DiffGUI() {
    setTitle("Diff");
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 600);
    this.contentPane = new JPanel();
    this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(this.contentPane);
    this.contentPane.setLayout(null);
    this.lblFile.setBounds(17, 6, 44, 16);

    this.contentPane.add(this.lblFile);
    this.textField.setBounds(61, 0, 265, 28);
    this.textField.setColumns(10);

    this.contentPane.add(this.textField);
    this.btnFile01.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            // Create a file chooser
            JFileChooser chooser = new JFileChooser();

            // Add filter for .txt files
            chooser.addChoosableFileFilter(new FileFilter());
            chooser.showOpenDialog(null);
            File file1 = chooser.getSelectedFile();

            // Write file name to text filed
            textField.setText(file1.getName());

            // Add file to array filenames
            filenames[0] = file1.getName();

        }
    });
    this.btnFile01.setBounds(327, 1, 117, 29);

    this.contentPane.add(this.btnFile01);
    this.lblFile_1.setBounds(17, 34, 44, 16);

    this.contentPane.add(this.lblFile_1);
    this.textField_1.setBounds(61, 28, 265, 28);
    this.textField_1.setColumns(10);

    this.contentPane.add(this.textField_1);
    this.btnFile02.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            // Create file chooser
            JFileChooser chooser= new JFileChooser();

            // Add filter for .txt files
            chooser.addChoosableFileFilter(new FileFilter());
            chooser.showOpenDialog(null);
            File file2 = chooser.getSelectedFile();

            // Write file name to text field
            textField_1.setText(file2.getName());

            // Add file to array filenames
            filenames[1] = file2.getName();

        }
    });
    this.btnFile02.setBounds(327, 29, 117, 29);

    this.contentPane.add(this.btnFile02);
    this.lblOutputFile.setBounds(17, 62, 81, 16);

    this.contentPane.add(this.lblOutputFile);
    this.textField_2.setBounds(97, 56, 347, 28);
    this.textField_2.setColumns(10);

    this.contentPane.add(this.textField_2);
    this.btnCompareFiles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });
    this.btnCompareFiles.setBounds(149, 94, 149, 43);

    this.contentPane.add(this.btnCompareFiles);
    this.textArea.setBounds(6, 149, 438, 423);

    this.contentPane.add(this.textArea);
}

/**
 * @return the filenames
 */
public String[] getFilenames() {
    return filenames;
}

/**
 * @param filenames the filenames to set
 */
public void setFilenames(String[] filenames) {
    this.filenames = filenames;
}
}
1
  • When you get an exception post the stacktrace and the relevant part of the code as well. Commented Mar 28, 2012 at 20:15

1 Answer 1

2

You're never calling setFilenames or setting the filenames variable explicitly - so it's always null. Then when you try to access the array:

filenames[0] = file1.getName();

that's always going to be dereferencing a null reference, and therefore throwing an exception.

You're never calling getFilenames() or setFilenames() as far as I can tell, so you should probably just remove them. I'm not sure why you're using an array to start with though - why don't you just have two string variables, leftFile and rightFile or something similar?

Sign up to request clarification or add additional context in comments.

3 Comments

If I have stored a file somewhere and reading that file on string, then its content will get store in that string but now if I want to get the name of that file then how I am going to do that...
@Reshma: It's not at all clear what you mean, I'm afraid - and it doesn't sound particularly related to this question. I suggest you read tinyurl.com/so-hints and then ask a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.