3

ファイルの最後の行を取得しようとしていますが、出力では見つからないことが示されています。また、すべての行が始まる "[" を探してみましたが、ジャンプが完璧でない限り、プログラムは "[" をスキップしません。「\r\n」、System.getProperty("line.separator")、\r、\nを探してみました。おそらくばかげた間違いですが、私が持っていて見つけられなかった場合、他の誰かがそれに遭遇する可能性があります.

        RandomAccessFile raf = new RandomAccessFile(fileLocation, "r");
        //Finds the end of the file, and takes a little more
        long lastSegment = raf.length() - 5;
        //**Looks for the new line character \n?**
        //if it cant find it then take 5 more and look again.
        while(stringBuffer.lastIndexOf("\n") == -1)  {
            lastSegment = lastSegment-5;
            raf.seek(lastSegment);
            //Not sure this is the best way to do it
            String seen = raf.readLine();
            stringBuffer.append(seen);
        }
        //Trying to debug it and understand
        int location = stringBuffer.lastIndexOf("\n");
        System.out.println(location);
        FileInputStream fis = new FileInputStream(fileLocation);
        InputStreamReader isr = new InputStreamReader(fis, "UTF8");
        BufferedReader br = new BufferedReader(isr);
        br.skip(lastSegment);
        System.out.println("br.readLine() " + br.readLine());
}

コードのアイデアは、テキスト ファイルの最後の行をすばやく読み取ることから来て います。

私が使用するファイルはこれです http://www.4shared.com/file/i4rXwEXz/file.html

助けてくれてありがとう、私のコードを改善できる他の場所があれば教えてください

4

1 に答える 1

6

を使用しているからですreadline。それが何であれ(CR / LF / CRLF)、改行文字String なしで行を返します。

Javadoc または RandomAccessFile#readLine() は次のように述べています。

テキストの行は、改行文字 ('\r')、改行文字 ('\n')、改行文字が直後に続く改行文字、またはファイルの終わりで終了します。行末文字は破棄され、返される文字列の一部には含まれません。

最後の行を見つけようとすると、ファイルを最後まで読むことができます。

于 2011-09-24T06:10:04.947 に答える