gpt4 book ai didi

java - 在Java中读取文本文件(.txt)时发生错误

转载 作者:行者123 更新时间:2023-12-01 15:02:57 25 4
gpt4 key购买 nike

我读取文本文件的java代码如下:

package practice.java;
import java.io.IOException;

public class SearchFiles {
public static void main(String[] args) throws IOException {
String file_name = "C:/Java/test.txt";

try {
ReadFile file = new ReadFile(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() );
}
}
}

以下是其他代码:

package practice.java;

import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class ReadFile {
private String path;

public ReadFile (String file_path) {
path = file_path;
}


public String[] OpenFile() throws IOException {

FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);

int numberOfLines = readLines();
String[] textData = new String[numberOfLines];

int i;

for (i=0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}

textReader.close();
return textData;
}

int readLines() throws IOException {

FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);

String aLine;
int numOfLines = 0;

while ((aLine = bf.readLine()) != null) {
numOfLines++;
}
bf.close();

return numOfLines;
}
}

结果为空。我究竟做错了什么?我应该纠正哪些部分?

最佳答案

您正在通读文件以确定行数。然后你尝试再次阅读它以实际阅读并捕获线条。这是很多不必要的工作。如果您使用List<String> ,您不需要这种两遍操作。试试这个:

public List<String> OpenFile() throws IOException {

List<String> lines = new ArrayList<String>();
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
try {
String aLine;
while ((aLine = bf.readLine()) != null) {
lines.add(aLine);
}
} finally {
textReader.close();
}
return lines;
}

如果您确实需要String[]而不是List<String> ,您可以将列表转换为数组。只需更改方法返回类型,然后替换行 return lines;与此:

    return lines.toArray(new String[0]);

关于java - 在Java中读取文本文件(.txt)时发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13372699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com