Reader // moves character around, have UTF handling
Writer // moves character around, have UTF handling
Uses:
Reading Writing files in program
Taking user input from console
Communicating through sockets
InputStream: FileInputStream, ByteArrayInputStream etc.
OutputStream: FileOutputStream, ByteArrayOutputStream etc.
Buffer
A buffer is a container for a fixed amount of data of a specific primitive type.
In addition to its content a buffer has:
position: index of the next element to be read or written
limit: which is the index of the first element that should not be read or written.
Program to read/write data from console
public class PersonCreator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter name, age and phone number: "); String name = scanner.next(); int age = scanner.nextInt(); Long phoneNumber = scanner.nextLong(); Person person = new Person(name, age, phoneNumber); }}
Program to read/write file
BufferedReader is synchronized and can be safely used in multithreaded application
BufferedReader is faster than Scanner
Scanner tokenizes the input and uses it
public class BufferedReaderExample { public static void main(String[] args) { File myFile = new File("example.txt"); try { BufferedReader reader = new BufferedReader(new FileReader(myFile)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException ex) { } }}
Try with resources
try with resources can be used on classes (called resource) which implements AutoClosable interface. Here BufferedReader and StringWriter are resources.
It automatically closes resources to prevent memory leaks
public class TryWithResourcesExample { public static void main(String[] args) { File myFile = new File("example.txt"); try ( BufferedReader reader = new BufferedReader(new StringReader("Hello World")); StringWriter writer = new StringWriter(); ) { writer.write(reader.ReadLine()); System.out.println(writer.toString()); } catch (IOException ex) { } }}