首页 > 解决方案 > 如何在另一个将读取文件的类中创建构造函数,然后在 main 方法中实例化它?

问题描述

我正在尝试使用文件类型的参数(例如,public TextRead(File textFile))创建一个构造函数。我将如何编写此构造函数,以便在 main 方法中实例化时会接收我在 main 方法中使用 JFileChooser 选择的文件?

我想简单地说,我将如何使用文件选择器将我选择的文件放入构造函数的参数中?我需要如何设置构造函数才能使其工作?

//My main method has this
public static void main(String[] args)
{
    JFileChooser fileChooser = new JFileChooser();
    Scanner in = null;
    if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    {
        //Constructor goes here to read the file I selected using the file chooser
    }
}

//The class that has the constructor
public class TextRead
{
    public TextRead(File textFile)
    {
        //What do I need to write here
    }
}

标签: javaswingfileconstructorjfilechooser

解决方案


根据本文档。你只需要使用fileChooser.getSelectedFile(). 那么你的代码应该是这样的

//My main method has this
public static void main(String[] args) {
    JFileChooser fileChooser = new JFileChooser();
    Scanner in = null;
    if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        //Constructor goes here to read the file I selected using the file chooser
        TextRead textRead = new TextRead(fileChooser.getSelectedFile());
    }
}

//The class that has the constructor
public class TextRead {
    private File file;  

    public TextRead(File textFile) {
        this.file = textFile; 
    }
}

推荐阅读