Как создать конструктор в другом классе, который будет читать файл, а затем создавать его экземпляр в методе main? - PullRequest
0 голосов
/ 30 января 2019

Я пытаюсь создать конструктор с параметром типа файла (например, 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
    }
}

1 Ответ

0 голосов
/ 30 января 2019

согласно этой документации .Вам нужно только использовать 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; 
    }
}
...