在两点之间读取文件

时间:2013-01-16 16:19:47

标签: java io newline readfile

我有以下文件:

FILE.CSV

header:2013/01/01, shasum: 495629218484151218892233214
content:data,a,s,d,f,g,h,j,k,l
content:data,q,w,e,r,t,y,u,i,o,p
content:data,z,x,c,v,b,n,m
footer:2013/01/01 EOF

我需要计算内容的哈希值。换句话说,我需要计算没有页眉和页脚的文件内容的哈希,并确保它与源头中提供的那个匹配。我尝试使用scanner逐行读取文件并省略页眉和页脚。

Scanner reader = new Scanner(new FileReader("filename"));
String header = reader.nextLine();
while(reader.hasNextLine()){
    line = reader.nextLine();
    if(reader.hasNextLine()){
        md.update(line.getBytes());
        md.update(NEW_LINE.getBytes());
    }
}

这里我不知道文件的来源。它可能来自Windows或Unix。那么我怎么知道要使用NEW_LINE。为此,我写了这个肮脏的黑客。

int i;
while((i = br.read()) != -1){
    if(i == '\r'){
        if(br.read() == '\n'){
            NEW_LINE = "\r\n";
            break;
        }
    } else if(i == '\n'){
        NEW_LINE = "\n";
        break;
    }
}

基本上它正在寻找\r\n\n的第一个序列。无论它首先遇到什么,它都假定它是换行符。

如果我的文件混合使用CRLF和LF,这肯定会给我带来麻烦。我可能会受益于一个我可以提供两个偏移量的读者,它可以让我回到这两个偏移之间的内容。像这样:

reader.read(15569, 236952265);

我相信我想要的两个偏移量可以计算出来。社区的任何建议都非常感谢。

1 个答案:

答案 0 :(得分:1)

比我在评论中的假设更好,我们应该只使用RandomAccessFile类!

// Load in the data file in read-only mode:
RandomAccessFile randFile = new RandomAccessFile("inputFileName.txt", "r");

// (On your own): Calculate starting byte to read from
// (On your own): Calculate ending byte to read from

// Discard header and footer.
randFile.setLength(endingPoint);
randFile.seek(startingPoint);

// Discard newlines of any kind as they are read in.
StringBuilder sb = new StringBuilder(endingPoint - startingPoint);
String currentLine = "";
while(currentLine != null)
{
  sb.append(currentLine);
  currentLine = randFile.readLine();
}

// hash your String contained in your StringBuilder without worrying about
// header, footer or newlines of any kind.

请注意,此代码不是生产质量,因为它不会捕获异常,并且可能会出现一些错误。我强烈建议您阅读RandomAccessFile类的文档:http://docs.oracle.com/javase/1.4.2/docs/api/java/io/RandomAccessFile.html#readLine()

我希望这会有所帮助。如果我不在基地,请告诉我,我会再给它一次。

相关问题