java - 如何在另一个将读取文件的类中创建构造函数,然后在 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
}
}
解决方案
根据本文档。你只需要使用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;
}
}
推荐阅读
- r - 使用 inputBox 的输出作为 R Shiny 中 inputSlider 的输入
- spring-cloud - 我们如何有条件地路由到 Spring Cloud Gateway 中的不同 URL?有参考样本吗?
- jquery - jQuery对每个div的输入值求和?
- angularjs - 当路径匹配时,使用响应注册的回调不会执行
- javascript - SVG 过滤器不绑定到它的图标
- python - PySImpleGui 错误代码 AttributeError:模块 'PySimpleGUI' 没有属性 'Popup'
- c# - 按下另一个键后,该键不再被视为“按下”
- c# - 如何修复我的代码以将已经存在的文件移动到另一个目录?
- python - 使用 pandas 的 sql 命令“OVER PARTITION”时出错
- c - C 文件中的结构数未知