1 JustOnly 1
1 JustOnly 1

Reputation: 293

Reading a String that has n length from InputStream or Reader

I know that I can do this. But I also want to know, is there a short way to do this ? For example: Why there is no method that has public String readString(int len); prototype in Reader class hierarchy to do what I want with only single code in this question ?

InputStream in = new FileInputStream("abc.txt");
InputStreamReader inReader = new InputStreamReader(in);
char[] foo = new char[5];
inReader.read(foo);
System.out.println(new String(foo));

// I think this way is too long
// for reading a string that has only 5 character
// from InputStream or Reader

In Python 3 programming language, I can do it very very easy for UTF-8 and another files. Consider the following code.

fl = open("abc.txt", mode="r", encoding="utf-8")
fl.read(1) # returns string that has 1 character
fl.read(3) # returns string that has 3 character

How can I dot it in Java ?

Thanks.

Upvotes: 0

Views: 1204

Answers (2)

Holger
Holger

Reputation: 298123

If you want to make a best effort to read as many as the specified number of characters, you may use

int len = 4;
String result;
try(Reader r = new FileReader("abc.txt")) {
    CharBuffer b = CharBuffer.allocate(len);
    do {} while(b.hasRemaining() && r.read(b) > 0);
    result = b.flip().toString();
}
System.out.println(result);

While the Reader may read less than the specified characters (depending on the underlying stream), it will read at least one character before returning or return -1 to signal the end of the stream. So the code above will loop until either, having read the requested number of characters or reached the end of the stream.

Though, a FileReader will usually read all requested characters in one go and read only less when reaching the end of the file.

Upvotes: 1

Andreas
Andreas

Reputation: 159086

How can I do it in Java ?

The way you're already doing it.

I'd recommend doing it in a reusable helper method, e.g.

final class IOUtil {
    public static String read(Reader in, int len) throws IOException {
        char[] buf = new char[len];
        int charsRead = in.read(buf);
        return (charsRead == -1 ? null : new String(buf, 0, charsRead));
    }
}

Then use it like this:

try (Reader in = Files.newBufferedReader(Paths.get("abc.txt"), StandardCharsets.UTF_8)) {
    System.out.println(IOUtil.read(in, 5));
}

Upvotes: 1

Related Questions