我是 Java 新手,这一切都是自学的。我喜欢使用代码,这只是一种爱好,因此,我没有接受过有关该主题的任何正规教育。
我现在正在学习从文本文件中读取内容。我得到的代码不正确。当我硬编码确切的行数时它可以工作,但是如果我使用“for”循环来感知有多少行,它就不起作用。
我对我得到的内容做了一些修改。这就是我现在所在的位置:
这是我的主课
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
这是我的类,它将读取文本文件并感知行数
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
请记住,我是自学成才的;我可能缩进不正确,或者可能会犯一些简单的错误,但请不要粗鲁。有人可以仔细检查一下,看看为什么它没有检测到行数 (int numberOfLines
) 以及为什么它无法工作,除非我硬编码 readLines()< 中的行数
方法。
最佳答案
问题是,您使用 int numberOfLines = 0; 将要读取的行数设置为零;
我宁愿建议使用行列表,然后将其转换为数组。
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
关于java - 从文本文件读取的代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700205/