Programming Tutorials

(追記) (追記ここまで)

CharArrayReader example program in Java

By: Abinaya in Java Tutorials on 2022年09月15日 [フレーム]

CharArrayReader is a subclass of Reader that allows you to read character data from a character array. Here's an example program that demonstrates its usage:

import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
public class CharArrayReaderExample {
 public static void main(String[] args) {
 char[] data = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' };
 try (Reader reader = new CharArrayReader(data)) {
 int c;
 while ((c = reader.read()) != -1) {
 System.out.print((char) c);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}

In this program, we create a character array containing the text "hello world", and then pass that array to a new instance of CharArrayReader. We then use a while loop to read the characters from the reader one at a time and print them to the console. When the end of the reader is reached (which occurs when reader.read() returns -1), the loop exits and the try block completes, causing the reader to be automatically closed.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /