IO streams Flashcards
(14 cards)
What is Java I/O?
Java I/O (Input/Output) is a set of APIs that allows reading from and writing to data sources like files, network sockets, memory, etc.
What are the two main types of I/O streams in Java?
Byte streams (handles binary data) and character streams (handles text data).
What is the difference between byte and character streams?
Byte streams (InputStream
, OutputStream
) process data as raw bytes; character streams (Reader
, Writer
) handle Unicode characters.
Which classes are used for reading from files using byte streams?
FileInputStream
for reading and FileOutputStream
for writing.
Which classes are used for reading and writing character data to files?
FileReader
and FileWriter
.
What is the purpose of using Buffered streams?
To improve efficiency by reducing I/O operations.
Example: BufferedReader
, BufferedWriter
, BufferedInputStream
, BufferedOutputStream
.
What is the standard I/O in Java?
System.in
(input), System.out
(output), System.err
(error stream).
What is the role of PrintWriter
in Java I/O?
It’s used for writing formatted representations of objects to text-output streams, including to files.
What is the try-with-resources statement?
A try block that automatically closes resources (like files) after execution. All classes must implement AutoCloseable
.
How do you read a line of text from a file using BufferedReader
?
```java
BufferedReader reader = new BufferedReader(new FileReader(“file.txt”));
String line = reader.readLine();
~~~
How do you write a string to a file using BufferedWriter
?
```java
BufferedWriter writer = new BufferedWriter(new FileWriter(“file.txt”));
writer.write(“Hello, world!”);
writer.close();
~~~
What exception must be handled or declared when using file I/O classes?
IOException
.
What is the use of Scanner
in file reading?
Scanner
can read data from a file easily using methods like next()
, nextLine()
, nextInt()
, etc.
Why is closing streams important?
To release system resources and avoid memory leaks.