2012-03-28 65 views
0

我試圖構建一個使用JFileChooser來選擇一個文件並將該文件的名稱存儲在String []數組中的GUI。我不能讓我的生活得到它的工作。它一直拋出IllegalArgumentException:文件名數組需要兩個文件名。 線程「AWT-EventQueue-0」中的異常java.lang.IllegalArgumentException:文件名數組需要兩個文件名。將一個文件的名稱放在一個String []數組中

我有一個diff類:

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; 
} 
} 

並有DiffGUI類:

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; 
} 
} 
+0

當你得到一個異常發佈stacktrace和代碼的相關部分。 – Robin 2012-03-28 20:15:45

回答

2

你永遠叫setFilenames或明確設置的filenames變量 - 所以它總是空。然後當您嘗試訪問陣列時:

filenames[0] = file1.getName(); 

這總是要解引用空引用,因此引發異常。

據我所知,你永遠不會打電話getFilenames()setFilenames()因此,你應該刪除它們。我不確定你爲什麼使用數組來開始 - 爲什麼你不只有兩個字符串變量,leftFilerightFile或類似的東西?

+0

如果我在某個地方存儲了一個文件並在字符串上讀取了該文件,那麼它的內容將獲得該字符串中的存儲,但是現在,如果我想獲取該文件的名稱,那麼我將如何執行該操作...... – Reshma 2013-11-15 06:51:06

+0

@Reshma :恐怕並不完全清楚你的意思 - 這與這個問題並沒有特別的關係。我建議你閱讀http://tinyurl.com/so-hints,然後問一個新問題。 – 2013-11-15 07:00:57

+0

plz按照下面的鏈接[http://stackoverflow.com/questions/19995251/to-get-the-file-name-in-string] – Reshma 2013-11-15 07:04:03

相關問題