Java 用于导入文件的构造函数
如果我想为一个类构建一个构造函数来导入一个文件,我已经在一个字符串nameOfFile中传递了这个文件,那么我如何初始化对象的状态,然后打开文档文件,并处理文档的每一行?请提供参考资料和明确解释。我刚刚开始学习java 为了澄清我的问题,如何为已导入的文档文件构建对象?我现在正在做的是,我已经编写了一个类,但我正在努力为一个特定的文件构建一个对象。到目前为止,我所知道的是Java 用于导入文件的构造函数,java,constructor,Java,Constructor,如果我想为一个类构建一个构造函数来导入一个文件,我已经在一个字符串nameOfFile中传递了这个文件,那么我如何初始化对象的状态,然后打开文档文件,并处理文档的每一行?请提供参考资料和明确解释。我刚刚开始学习java 为了澄清我的问题,如何为已导入的文档文件构建对象?我现在正在做的是,我已经编写了一个类,但我正在努力为一个特定的文件构建一个对象。到目前为止,我所知道的是 public class theImport { theImport(String nameOfFile) { (Her
public class theImport
{
theImport(String nameOfFile)
{
(Here is where I want to achieve all the listing I have above.)
}
.
.
.
}
我相信你会分两步来做 第一步:实际的构造函数
private String nOF;
public ClassName(String nameOfFile) {
nOF = nameOfFile;
}
第二步:评估文件。由于各种原因(例如,文件不存在,它不应该转到构造函数(您无法从构造函数中没有的返回类型捕获这些错误),因此此操作可能会失败
我的Java目前还不是最好的,但这应该给你指明正确的方向。也许你的意思是这样的:
public class theImport
{
theImport(String nameOfFile)
{
try {
FileReader input = new FileReader(nameOfFile);
BufferedReader bufRead = new BufferedReader(input);
String line;
line = bufRead.readLine();
//this will loop thought the lines of the file
while (line != null){
line = bufRead.readLine();
//do whatever you want with the line
}
bufRead.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
“初始化对象的状态”是什么意思?通过调用构造函数,您正在初始化对象。您可以通过在文件中添加一些示例数据来改进您的问题,并演示您试图实现的目标。否则,看起来您这里有一个复制粘贴(家庭作业)问题,要求完整的解决方案。
public class theImport
{
theImport(String nameOfFile)
{
try {
FileReader input = new FileReader(nameOfFile);
BufferedReader bufRead = new BufferedReader(input);
String line;
line = bufRead.readLine();
//this will loop thought the lines of the file
while (line != null){
line = bufRead.readLine();
//do whatever you want with the line
}
bufRead.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}