无法在文件中找到换行符(java)

时间:2011-09-24 05:29:43

标签: java file-io newline fileinputstream random-access

我正在尝试获取文件的最后一行,但我的输出显示它从未找到它。我也尝试寻找所有行开头的“[”,但除非跳转完美,否则程序不会跳过“[”。我试着寻找“\ 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());
}

代码中的想法来自 Quickly read the last line of a text file?

我使用的文件就是这个 http://www.4shared.com/file/i4rXwEXz/file.html

感谢您的帮助,如果您看到我的代码可以改进的任何其他地方,请告诉我

2 个答案:

答案 0 :(得分:7)

这只是因为您使用的是readline。 它返回行String ,不带换行符(CR / LF / CRLF)。

Javadoc或RandomAccessFile #readLine()说:

  

一行文本以回车字符('\ r'),换行符('\ n'),回车字符后面紧跟换行字符或文件末尾终止。行终止字符将被丢弃,并且不会作为返回字符串的一部分包含在内。

如果您尝试查找最后一行,则可以将文件读到最后一行。

答案 1 :(得分:-1)

我想分享我得到的代码。抱歉延迟

RandomAccessFile raf = new RandomAccessFile(fileLocation, "r");
    long lastSegment = raf.length();
    //if you sure the last sentence is longer, you can change the 3 to higher value
    lastSegment = lastSegment-3;
    raf.seek(lastSegment);
    byte array[] = new byte[1024];
    raf.read(array);
    String seen = new String(array);
    stringBuffer.append(seen);

    int location = stringBuffer.lastIndexOf("\n");
    //Last line ends with \n so I need to make sure I get the 2nd to last
    while(stringBuffer.indexOf("\n") == stringBuffer.lastIndexOf("\n"))  {
        location = stringBuffer.indexOf("\n");
        //How fast you want to jump, large number 
        //quicker answer but if lines can be short then you may skip 1 by accident
        lastSegment = lastSegment-5;
        raf.seek(lastSegment);
        raf.read(array);
        seen= new String(array);
        stringBuffer = new StringBuffer(seen);
    }
    FileInputStream fis = new FileInputStream(fileLocation);
    InputStreamReader isr = new InputStreamReader(fis, "UTF8");
    BufferedReader br = new BufferedReader(isr);
    br.skip(lastSegment + stringBuffer.indexOf("\n") + 1);
    System.out.println("Last Line: " + br.readLine());