关于Java文件读取器的问题
我在使用 FileReader 类时遇到一些问题。
如何指定它所经过的线路的偏移量,以及如何告诉它何时停止? 假设我希望它遍历 .txt 文件中的每一行,但只遍历 100-200 行,然后停止?
我该怎么做?现在我正在使用 ReadLine() 但我认为没有办法指定偏移量。
非常感谢任何快速帮助。谢谢。
I'm having some problems with the FileReader class.
How do I specify an offset in the lines it goes through, and how do I tell it when to stop?
Let's say I want it to go through each line in a .txt file, but only lines 100-200 and then stop?
How would I do this? Right now I'm using ReadLine() but I don't think there's a way to specify offset with that.
Any fast help is VERY appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。 FileReader 一次读取一个字符或一次读取一行。显然,您可以编写自己的代码来扩展或包装它以跳到不需要的行。
但
旁白:使用 FileReader 或 FileWriter 时要小心 - 它们使用默认的 LOCALE 字符集。如果要强制使用字符集,请使用 OutputStreamWriter 或 InputStreamReader。示例
Writer w = new FileWriter(file) 可以替换为
Writer w = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); <=== 看看如何设置字符集。
You can't. FileReader reads a character at a time or a line at a time. Obviously you can write your own code extending or wrapping it to skip to the unneeded lines.
An aside: Be CAREFUL using FileReader or FileWriter - they use the default LOCALE character set. If you want to force a character set use OutputStreamWriter or InputStreamReader. Example
Writer w = new FileWriter(file) can be replaced by
Writer w = new OutputStreamWriter(new FileOutputStream(file),"UTF-8"); <=== see how I can set the character set.
读取所有行,但使用另一个变量来计算您所在的行。如果您不想处理某一行(例如,第 100 行之前),请调用
continue
;如果您不想再处理更多行,请调用break
(第 200 行之后)。Read all the lines but use another variable to count which line you are on. Call
continue
if you are on a line that you don't want to process (say, before the 100th line) andbreak
when you will not want to process any more lines (after the 200th line).没有办法告诉读者只阅读某些行,您可以使用计数器来做到这一点。
There is not a way to tell the reader to only read certain lines, you can just use a counter to do it.