我正在尝试创建一个带有文件类型参数的构造函数(例如,公共TextRead(File textFile))。我将如何编写此构造函数,以便在main方法中实例化时可以使用在我使用JFileChooser在main方法中选择的文件中?
我想简单地说一下,我如何将使用文件选择器选择的文件放入构造函数的参数中?我需要如何设置构造函数才能使其正常工作?
//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
}
}
答案 0 :(得分:0)
根据this documentation。您只需要使用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;
}
}