簡體   English   中英

如何在另一個將讀取文件然后在main方法中實例化的類中創建構造函數?

[英]How to create a constructor in another class that will read a file, then instantiate it in the main method?

我正在嘗試使用文件類型的參數(例如,公共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
    }
}

根據此文檔 您只需要使用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; 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM