【问题标题】:Java : How to read a File line by line including different line separatorJava:如何逐行读取文件,包括不同的行分隔符
【发布时间】:2016-02-24 20:34:45
【问题描述】:

我们正在使用 JAVA 8 和

这是我的问题的背景:

我们的程序中有这样的地图:

<Key, object containing (record-offset, record-lentgh)

我们必须计算文件中每条记录的长度,应该包含行分隔符来计算每条记录的记录偏移量。 例如:

record-offset of 1st record in the file  = 0
record-offset of 2nd record in the file  = 
                                record-offset of 1st record in the file 
                                + record length of 1st record

and so on...

在后面的过程中,我们将使用这些记录偏移量和记录长度信息通过 RandomAccessFile 从文件中读取每条记录。

这个过程很快,并且在运行期间为我们节省了内存。

现在的问题是:

当我使用 BefferedReader.readLine() 读取文件中的每条记录并根据返回的字符串的长度计算记录长度和记录偏移量时,这个记录偏移量计算被搞砸了。 BefferedReader 删除行分隔符。 DOS 文件的行分隔符为 \r\n,Unix/MAC 文件的行分隔符为 \n。因此,我使用 RandomAccessFile 读取文件的后一个过程由于偏移量错误而搞砸了。看起来要解决我必须以这种方式从第二条记录开始计算偏移量的问题:

line-separator-length  = 2;\\for DOS or 1 for UNix type file 
record-offset of 2nd record in the file  = 
                 record-offset of 1st record in the file 
                 + record length of 1st record 
                 + line-separator-length

因此,我的问题是:

  • 是否可以从包含行分隔符的文件中读取每一行(这样我就不必担心文件的类型)?

  • 有什么方法可以确定它来自 JAVA 的文件类型? (DOS/UNIX/MAC)

  • 有什么方法可以检查文件中的行分隔符是什么?

提前致谢。

【问题讨论】:

  • 这看起来像 3 个问题,而不是 1 个。

标签: java filereader


【解决方案1】:

是否可以从包含行分隔符的文件中读取每一行?

当然。使用 BufferedReader 作为模型扩展抽象类 Reader。包括行分隔符。

有什么方法可以确定它来自什么类型的文件?

当然。 Unix 以换行符 (\n) 结束,Windows 以回车符、换行符 (\r\n) 结束,Mac (OS 10+) 以换行符 (\n) 结束。

较旧的 Mac 以回车符 (\r) 结尾。

有什么方法可以检查文件中的行分隔符是什么?

您的 Reader 类将返回字符串最后或最后 2 个位置的行分隔符。

【讨论】:

    【解决方案2】:

    这就是我解决问题的方法:感谢以下讨论: How to find out which line separator BufferedReader#readLine() used to split the line?

    public int getLineTerminatorLength( String filePath ) throws FileUtilitiesException
    {
        try (BufferedReader tempreader = FileUtilities.getBufferedReader( new File( filePath ) ))
        {
    
            String l = "";
            char termChar = ' ';
    
            while ( ( termChar = (char) tempreader.read() ) != -1 )
            {
    
                if ( ( termChar == '\n' ) || ( termChar == '\r' ) )
                {
                    char ctwo = ' ';
                    if ( ( ctwo = (char) tempreader.read() ) != -1 )
                    {
                        if ( ( ctwo == '\n' ) || ( ctwo == '\r' ) )
                            return 2;
                    }
    
                    return 1;
    
                }
    
            }
    
        }
        catch ( Exception e )
        {
            String errMsg = "Error reading file  " + filePath;
            throw new FileUtilitiesException( errMsg );
        }
    
        //Will reach here if it is empty file
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 2023-01-01
      • 1970-01-01
      相关资源
      最近更新 更多