我有以下代码可以从 CSV 中读取:
InputStream inp = getClass().getResourceAsStream(filename);
InputStreamReader r = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(r);
关于已回答的问题:
Java BufferedReader ,
Convert InputStream to BufferedReader , What is the difference between Java's BufferedReader and InputStreamReader classes?
BufferedReader[BR] 和 InputStreamReader[ISR] 都实现相同的接口(interface)。 BR 拥有 ISR 拥有的所有方法以及额外的方法,包括非常有用的 readLine() 方法和不太有用但仍然相关的 skip() 方法。您不一定需要 BR 来读取单个字符,尽管 BR 在这方面可以比 ISR 更有效地完成同样的工作。唯一显着的区别是 FileReader 是 ISR 而不是 BR 的子类,尽管我在这个网站上有消息称由于替代品,FileReader 不再真正使用。
我的研究表明,ISR 能做的所有事情,BR 都能做得更好。我是一名年轻的开发人员,所以每个定义或导入的类对我来说似乎都是相关的。我想了解的是,如果不再使用某些类,而用新版本或框架代替它们。我想知道更有经验的开发人员会说些什么。那么,有没有理由在使用 ISR 时不使用 BR?
API 快速链接:
BufferedReader
InputStreamReader
最佳答案
我在您的帖子中看到一些关于 ISR 和 BR 的混淆。
1) 你是说
My research says that everything ISR can do is done better by BR
但是让我们看看它们每个的 JavaDoc:
情报侦察
public class InputStreamReader extends Reader
An InputStreamReader is a bridge from byte streams to character streams:
BR
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
如您所见,ISR 将字节转换为字符。 BR 另一方面需要字符。这就是为什么 BR 需要使用 ISR 来读取 InputStream
。
2) 至于最初的问题,为什么不直接使用 ISR。您肯定可以这样做,但为了获得性能,您需要使用 BR。你可能会问为什么不使用缓冲来实现 ISR?因为 ISR 旨在做好一件事,那就是读取字节并将其转换为字符。缓冲部分被移动到 BR 的 Decorator 类中。这样做是为了能够为任何阅读器添加缓冲功能,而不仅仅是 ISR。
关于java - 是否有理由不使用 BufferedReader 包装 InputStreamReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44440935/