0

我读取文本文件的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;
        }
    }

结果是空的。我究竟做错了什么?我要纠正哪些部分?

4

1 回答 1

1

您正在阅读文件以确定行数。然后您尝试再次阅读它以实际阅读和捕获这些行。这是很多不必要的工作。如果您使用 a 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;
}

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

    return lines.toArray(new String[0]);
于 2012-11-14T03:49:49.903 回答