Java I/O Streams
Java I/O Streams
Java I/O Streams are used for reading or writing information that are on an external source.
Java I/O Streams allow communication between two or more threads.
In Java there are two types of streams:
- Byte Streams
- Character Streams
Classes that perform input and output operations are stored in the package java.io.
The main classes of java.io package are: File, FileReader, FileWriter, FileInputStream, FileOutputStream, InputStreamReader, OutputStreamWriter, DataInputStream, DataOutputStream, BufferedReader, BufferedWriter, PrintStream, PrintWriter.
Streams example
Example 1
import java.io.*; public class CreateWriteFile{ public static void main(String [] args){ try{ String filetxt = "Test write file from java."; PrintStream output = new PrintStream("myfile1.txt"); output.println(filetxt); output.close(); }catch(Exception ex){ System.out.println("Java Error!"); } } }
Example 2
import java.io.*; public class CopyString { public static void main(String args[]) throws IOException { FileReader input = null; FileWriter output = null; try { input = new FileReader("input_file.txt"); output = new FileWriter("output_file.txt"); int s; while ((s = input.read()) != -1) { output.write(s); } }catch(Exception ex){ System.out.println("Java Error!"); }finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } }