Rollerball
Rollerball

Reputation: 13118

Why is there no FileReader.read(String), when FileWriter has write(String)

I have noticed that in FileWriter there is a method to write a String: .write(String), whereas in FileReader there is only the possibility to read into a array of char.

Is there a reason behind it?

Upvotes: 2

Views: 1798

Answers (4)

Joni
Joni

Reputation: 111379

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.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

The String class is immutable so it would be impossible to "read into a String". On the other hand, if you just meant String read(), then the problem there is that you haven't communicated the size of the string you wish to read. Yes, there could be a method String read(int), which would say how much you want to read at once, but since the step from char[] to String is very simple, there was no need for a second method like that. read(char[]), on the other hand is a much more versatile – and efficient – method.

Upvotes: 4

tbodt
tbodt

Reputation: 17007

In FileWriter, it is easy to write a String. However, in FileReader, there is no way to read a String, because it doesn't know when to stop. If it reads into a char[], it can't read past the end of the array. If you want to read one line at a time, then create a BufferedReader, which has a method to read and return one line as a string. If you want to read a specific amount of characters into a string, you could write yourself a helper method:

public static String read(Reader in, int n) {
    char[] chars = new char[n];
    in.read(chars);
    return new String(chars);
}

Upvotes: 0

Thilo
Thilo

Reputation: 262824

If you can "upgrade" to BufferedReader,you get a readLine that does indeed return a String.

Upvotes: 0

Related Questions