【发布时间】:2015-03-12 02:45:19
【问题描述】:
我正在尝试按照一段代码打开和读取文本文件。为此,我有一个名为 readText 的包。我在其中构建了一个 readLocalFile 类来打开和读取文件,以及一个调用它的 main 方法。下面是这两个类。
public class readFileLocal {
private String path;
public readFileLocal(String file_path){
path = file_path;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader lines = new BufferedReader (file_to_read);
int numberOfLines = 0;
while(lines.readLine()!= null) {
numberOfLines ++;
}
lines.close();
return numberOfLines;
}
public String[] openFile() throws IOException{
FileReader freader = new FileReader (path);
BufferedReader textReader = new BufferedReader (freader);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i; /* put all the lines of text from the file to the array*/
for (i=0; i<numberOfLines; i++){
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
然后我有一个主类来调用它。代码如下:
public class fileData {
public static void main(String[] args) throws IOException{
String file_name = "F:/Testfile.exl";
try{
readFileLocal file = new readFileLocal(file_name);
String[] arylines = file.openFile();
int i;
for (i=0; i<arylines.length; i++){
System.out.println(arylines[i]);
}
}
catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
当我运行它时,Eclipse 给了我这个错误消息:
错误:在 readText.fileData 类中找不到主方法,请将主方法定义为:public static void main(String[] args) 或 JavaFX 应用程序类必须扩展 javafx.application.Application
知道出了什么问题吗?
【问题讨论】:
-
你在项目中是否设置了 readFileLocal 作为启动类?类都大写也是惯例。
-
什么是“创业班”,我该怎么做? Java新手。谢谢。
-
在包资源管理器中,尝试右键单击包含 main 方法的类并从那里选择运行。正如 Lachlan 所说,您应该学习并遵循命名约定。 Java 中的命名约定非常强大,以至于不遵循它们会使有经验的程序员稍微感到困惑。 (例如,
fileData看起来像一个变量名,而不是类名。) -
您的每个类是否都定义在自己的文件中,并根据它们的包层次结构在正确的文件夹中?
-
将对命名约定做一点研究。我确实从 main 方法运行并得到了错误。
标签: java