java - 将文件名放入 String[] 数组中

标签 java

我正在尝试构建一个 GUI,它使用 JFileChooser 选择文件并将文件名存储在 String[] 数组中。我一辈子都无法让它发挥作用。它不断抛出 IllegalArgumentException:文件名数组中需要两个文件名。 线程“AWT-EventQueue-0”中出现异常 java.lang.IllegalArgumentException:文件名数组中需要两个文件名。

我有一个差异类:

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

最佳答案

您永远不会显式调用 setFilenames 或设置 filenames 变量 - 因此它始终为 null。然后当您尝试访问数组时:

filenames[0] = file1.getName();

这总是会取消引用空引用,从而引发异常。

据我所知,你永远不会调用 getFilenames() setFilenames(),所以你应该删除它们。我不确定为什么你要使用数组来开始 - 为什么你不只有两个字符串变量,leftFilerightFile或类似的东西?

关于java - 将文件名放入 String[] 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9914938/

相关文章:

java - 时间戳解析失败

java - 我可以向未明确定义的 JButton 添加 ActionListener 吗?

java - 从 IntelliJ IDEA JBoss 迁移到 MyEclipse Tomcat 后出现 Unsupported major.minor version 51.0 错误

java - 为什么android隐藏蓝牙mac地址?

java.lang.ClassCastException : [Ljava. lang.Object;无法转换为 rmc.entity.UserEntity

java - doInBackground 卡住了

java - 装箱值被取消装箱,然后立即重新装箱 - Double

java - 如何在 java fx 中每 2 秒更新一次标签框?

java - 如何使用 Kotlin 在 View 模型中使用 TextInputLayout 设置错误标签

java - 将新对象添加到数组时,对象被覆盖