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

行数を決定するためにファイルを読み込んでいます。次に、実際に行を読み取ってキャプチャするために、もう一度読み取ろうとします。これは多くの不必要な作業です。を使用する場合List<String>、この 2 パス操作は必要ありません。代わりにこれを試してください:

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]);
于 2012-11-14T03:49:49.903 に答える