简体   繁体   English

从文件Java中读取错误的字符

[英]Reading wrong characters from file Java

I am reading characters from file by skipping 2 times 我通过跳过2次从文件中读取字符

     fis = new FileInputStream("C:/data/25130.in ");
     fis.skip(24305);//This position contains _(UnderScore)
     l=fis.read();
     fis.skip(24312);//This position also contains _(Underscore)
     i = fis.read();
     ch= (char)l;
     c = (char)i;
     System.out.print("Ch: "+ch);//Returns Underscore
     System.out.print("C: "+c); // Returns 9 instead of UnderScore

If i delete the fist skip like the following 如果我删除拳头跳过如下

     fis = new FileInputStream("C:/data/25130.in ");         
     fis.skip(24312);//This position also contains _(underscore)
     i = fis.read();
     c = (char)i;
     System.out.print("C: "+c); // Now it returns Underscore

I intend to read 2 characters at 2 positions..Where was the problem 我打算在2个位置读2个字符。问题出在哪里

fis.skip(24312) skips that many characters (it reads 24312 bytes and throws them away....) fis.skip(24312)跳过那么多字符(它读取24312个字节并将它们扔掉......)

What you want to do is "position" the input stream, and throw away only (24312 - 24305) bytes, or fis.skip(7) 你想要做的是“定位”输入流,只扔掉(24312 - 24305)字节,或fis.skip(7)

EDIT: hmmm, lutzh is right, you want to fis.skip(6) but.... 编辑:嗯,lutzh是对的,你想fis.skip(6)但....

what you really want to do is use a RandomAccessFile and use the seek(position) method... 你真正想做的是使用RandomAccessFile并使用搜索(位置)方法......

I think FileInputStream.skip does not go to the given position, it skips the given number of bytes. 我认为FileInputStream.skip不会到达给定位置,它会跳过给定的字节数。 So after your second skip you will end up at 48617, plus one more that you actually read. 所以在你的第二次跳过后,你将最终得到48617,还有一个你真正读过的。

Try 6 as parameter for your second skip. 尝试6作为第二次跳过的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM