![](/img/trans.png)
[英]How can I pass an object array to a method in another class so this method uses it as a normal array?
[英]How can I pass a filename String to another Class so that it creates a File object in that class?
我有一个文件 object 在名为 ReadFiles 的 class 中创建。
public class ReadFiles {
File file = new File("google.csv");
}
如上所述使用一组“google.csv”输入时,文件创建工作。
我想要做的是从另一个 class StockBuySell 传递一个字符串文件名,这样它在 ReadFiles 中创建的文件是基于字符串文件名创建的。 这是我尝试过的:
public class ReadFiles {
String filename;
public ReadFiles(String filename) {
this.filename = filename;
}
File file = new File(filename);
}
在同一个 package 中的另一个 class 中:
public class StockBuySell {
ReadFiles googleData = new ReadFiles("google.csv");
}
我得到一个 NullPointerException。 我相信这是因为该文件不是由我的方法创建的。 我能做些什么? 谢谢您的帮助。
编辑:我意识到由于与读取文件相关的其他方法,我遇到了错误。 我最终使用 hata 的方法来创建一个文件。 感谢你们!
你想要达到的目标是这样的吗?:
public class ReadFiles {
File file;
public ReadFiles(String filename) {
file = new File(filename);
}
}
NullPointerException 的原因应该是字段File file = new File(filename);
. 在调用 Constructor 方法之前, filename
最初是 null。
初始化的顺序有点不稳定; 首先运行所有“实例初始化程序”(分配给字段的表达式是其中的一部分),然后才运行构造函数。 因此:
public class ReadFiles {
private final String filename;
private final File file;
public ReadFiles(String name) {
this.filename = filename;
this.file = new File(filename); // put it here.
}
}
不过,这段代码有各种各样的问题。 它使用的是旧的 API,并且命名不正确。 (此代码正在读取 1 个文件,但名为“ReadFiles”。此外,类不应以动词命名,它应该描述它所代表的内容,而不是它的作用。它还有一个额外的,大部分无用的字段。
解决所有问题:
public class CsvReader {
private final Path file;
public CsvReader(String path) {
this.file = Paths.get(path);
}
public CsvReader(Path path) {
this.path = path;
}
}
然后我们又遇到了另一个问题:读取 csvs 听起来很简单,但事实并非如此。 使用诸如OpenCSV 之类的库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.