2

我注意到FileWriter有一种方法可以写入 String: .write(String),而FileReader只有读入 char 数组的可能性

这背后有什么原因吗?

4

4 回答 4

4

该类String是不可变的,因此不可能“读入字符串”。另一方面,如果您只是说String read(),那么问题在于您没有传达您希望阅读的字符串的大小。是的,可能有一个方法String read(int),它会说你想一次读多少,但是由于从char[]到的步骤String非常简单,所以不需要像这样的第二种方法。read(char[]),另一方面是一种更加通用且高效的方法。

于 2013-07-28T07:37:04.107 回答
0

Strings are immutable, which is another way of saying that once you create a string you can't change it, for example to reuse the storage space it occupies. If there was a method in Reader that returned a string it would have to create a new string every time you call it, leading to the creation of a lot of garbage.

Also the semantics of such a method would not be clear: should it read as many characters as can be read without blocking, like the other read methods? That's probably not very useful. Should it read some sensible unit of text, like a line? That requires buffering, and should be the responsibility of a different class.

于 2013-07-28T07:49:34.257 回答
0

如果你可以“升级”到 BufferedReader,你会得到一个readLine确实返回一个字符串的。

于 2013-07-28T07:36:54.243 回答
0

FileWriter中,很容易编写String. 但是,在 中FileReader,没有办法读取 a String,因为它不知道何时停止。如果它读入 a char[],它就不能读到数组的末尾。如果您想一次读取一行,则创建一个BufferedReader,它具有读取并以字符串形式返回一行的方法。如果您想将特定数量的字符读入字符串,您可以自己编写一个辅助方法:

public static String read(Reader in, int n) {
    char[] chars = new char[n];
    in.read(chars);
    return new String(chars);
}
于 2013-07-28T07:42:19.070 回答