How to make I/O Statement in Java
No matter which programming language one chooses, performing input and output operations are the core knowledge that one definitely needs to posses. From disk files, devices, other programs to memory arrays, a stream can represent a variety of data sources and destinations. This article will teach you how to use the four most important input and output streams in Java.
Method One of Four:
Using Byte and Character Streams
Byte streams handle input and output of raw binary data, byte by byte. Raw binary data is the type of data that hasn't been processed yet, bunch of ones and zeroes.
Character streams handle and translate input and output of character data, character by character. Translation, in this case, means that character streams automatically transform character format from and to the local character set.
Character streams handle and translate input and output of character data, character by character. Translation, in this case, means that character streams automatically transform character format from and to the local character set.
- 1Create a text file. Give it an arbitrary name and write something in it, such as I love wikiHow!. In this article, we will name it file.txt.
- 2Create a main method. You can add throws IOException declaration to the method signature to avoid adding the catch block to the try-with-resources block.
public static void main(String[] args) { }
- 3Create a try-with-resources block.Try-with-resources block will automatically close streams for us.
public static void main(String[] args) { try () { } }
- 4Create
FileInputStreamorFileReaderin the block statement. In the constructor of the created input stream, specify the name of the text file previously created. In this article, we called it file.txt.public static void main(String[] args) { try (FileInputStream in = new FileInputStream("file.txt")) { } }
- The former is a byte stream, the latter is a character stream.
- 5Create
FileOutputStreamorFileWriterin the block statement. In the constructor of the created output stream, specify another arbitrary text file name. In this article, we will name it file-copy.txt.public static void main(String[] args) { try ( FileInputStream in = new FileInputStream("file.txt"); FileOutputStream out = new FileOutputStream("file-copy.txt") ) { } }
- If you created
FileInputStream, you need to createFileOutputStream. The same goes for theFileReaderandFileWriter. - 6Create
intvariable. This variable will be used for temporary storage of read byte or character.public static void main(String[] args) { try ( FileInputStream in = new FileInputStream("file.txt"); FileOutputStream out = new FileOutputStream("file-copy.txt") ) { int data; } }
- 7Read data from input stream. Create a while loop in which the data is read into the previously created
intvariable until it reads the number-1. In other words, it reads data from the file until it reaches the end of the file.public static void main(String[] args) { try ( FileInputStream in = new FileInputStream("file.txt"); FileOutputStream out = new FileOutputStream("file-copy.txt") ) { int data; while ((data = in.read()) != -1) { } } }
- 8Write data to the output stream. In the body of the while loop, write the read data to the output stream.
public static void main(String[] args) { try ( FileInputStream in = new FileInputStream("file.txt"); FileOutputStream out = new FileOutputStream("file-copy.txt") ) { int data; while ((data = in.read()) != -1) { out.write(data); } } }
- 9Catch and handle IOException. Add a catch block to the try-with-resources block, catch
IOExceptionand, in case of an error, print the stack trace to the console.public static void main(String[] args) { try ( FileInputStream in = new FileInputStream("file.txt"); FileOutputStream out = new FileOutputStream("file-copy.txt") ) { int data; while ((data = in.read()) != -1) { out.write(data); } } catch (IOException e) { e.printStackTrace(); } }
- 10Run the program. Contents of the
file.txtare copied to thefile-copy.txtwhich, if it doesn't exist yet, is createdMethod Two of Four:
Using Buffered StreamsBuffered streams optimize input and output data. Buffer streams are more efficient than byte and character streams as they read and write from a buffer that is handled by Java platform rather than the underlying operating system. Most common usage of buffered streams is reading a textual file, line by line.- 1Create a text file. Give it an arbitrary name and write something in it, such as I love wikiHow!. In this article, we will name it file.txt.
- 2Create a main method. You can add throws IOException declaration to the method signature to avoid adding the catch block to the try-with-resources block.
public static void main(String[] args) { }
- 3Create a try-with-resources block.Try-with-resources block will automatically close streams for us.
public static void main(String[] args) { try () { } }
- 4Create
BufferedReaderin the block statement. In the constructor of the created input stream, create aFileReaderand specify the name of the text file previously created inside its constructor. In this article, we called it file.txt.public static void main(String[] args) { try (BufferedReader in = new BufferedReader(new FileReader("file.txt"))) { } }
- 5Create
BufferedWriterin the block statement. In the constructor of the created output stream, create aFileWriterand specify another arbitrary text file name in its constructor. In this article, we will name it file-copy.txt.public static void main(String[] args) { try ( BufferedReader in = new BufferedReader(new FileReader("file.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("file-copy.txt")) ) { } }
- 6Create
Stringvariable. This variable will be used for temporary storage of read lines.public static void main(String[] args) { try ( BufferedReader in = new BufferedReader(new FileReader("file.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("file-copy.txt")) ) { String line; } }
- 7Read lines from input stream. Create a while loop in which the lines are read into the previously created
Stringvariable until it readsnull. In other words, it reads data from the file until it reaches the end of the file.public static void main(String[] args) { try ( BufferedReader in = new BufferedReader(new FileReader("file.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("file-copy.txt")) ) { String line; while ((line = in.readLine()) != null) { } } }
- 8Write lines to the output stream with line separator. In the body of the while loop, write the read lines to the output stream and append the line separator at the end of each line.
BufferedReaderreads lines, but omits the line separator.public static void main(String[] args) { try ( BufferedReader in = new BufferedReader(new FileReader("file.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("file-copy.txt")) ) { String line; while ((line = in.readLine()) != null) { out.write(line + System.lineSeparator()); } } }
- 9Catch and handle IOException. Add a catch block to the try-with-resources block, catch
IOExceptionand, in case of an error, print the stack trace to the console.public static void main(String[] args) { try ( BufferedReader in = new BufferedReader(new FileReader("file.txt")); BufferedWriter out = new BufferedWriter(new FileWriter("file-copy.txt")) ) { String line; while ((line = in.readLine()) != null) { out.write(line + System.lineSeparator()); } } catch (IOException e) { e.printStackTrace(); } }
- 10Run the program. Contents of the
file.txtare copied to thefile-copy.txtwhich, if it doesn't exist yet, is created. Method Three of Four:
Using Data StreamsData streams handle binary input and output of primitive data types and Strings. Data streams make it very easy to read and writeboolean,char,byte,short,int,long,float,doubleandStringvalues. Most common usage of data streams is in network applications (e.g. instant messengers).- 1Create a main method. You can add throws IOException declaration to the method signature to avoid adding the catch block to the try-with-resources block.
public static void main(String[] args) { }
- 2Create a try-with-resources block.Try-with-resources block will automatically close streams for us.
public static void main(String[] args) { try () { } }
- 3Create
DataOutputStreamin the block statement. In the constructor of the created input stream, createFileOutputStreamand specify an arbitrary file name inside its constructor. In this article, we will name it file.txt.public static void main(String[] args) { try (DataOutputStream out = new DataOutputStream(new FileOutputStream("file.txt"))) { } }
- 4Create
DataInputStreamin the block statement. In the constructor of the created input stream, create aFileInputStreamand specify file name from the previous step inside its constructor. In this article, we named it file.txt.public static void main(String[] args) { try ( DataOutputStream out = new DataOutputStream(new FileOutputStream("file.txt")); DataInputStream in = new DataInputStream(new FileInputStream("file.txt")) ) { } }
- 5Write some data to the output stream.In the body of the try-with-resources block, write String,
boolean,intand other primitive data to the output stream.public static void main(String[] args) { try ( DataOutputStream out = new DataOutputStream(new FileOutputStream("file.txt")); DataInputStream in = new DataInputStream(new FileInputStream("file.txt")) ) { out.writeUTF("wikiHow is a great place to learn"); out.writeBoolean(true); out.writeInt(10430); out.writeDouble(20.9d); out.writeFloat(23.10f); } }
- 6Read data from the input stream and print it. Read the data in the same order as it has been written and print it to the console.
public static void main(String[] args) { try ( DataOutputStream out = new DataOutputStream(new FileOutputStream("file.txt")); DataInputStream in = new DataInputStream(new FileInputStream("file.txt")) ) { out.writeUTF("wikiHow is a great place to learn"); out.writeBoolean(true); out.writeInt(10430); out.writeDouble(20.9d); out.writeFloat(23.10f); System.out.println(in.readUTF()); System.out.println(in.readBoolean()); System.out.println(in.readInt()); System.out.println(in.readDouble()); System.out.println(in.readFloat()); } }
- 7Catch and handle IOException. Add a catch block to the try-with-resources block, catch
IOExceptionand, in case of an error, print the stack trace to the console.public static void main(String[] args) { try ( DataOutputStream out = new DataOutputStream(new FileOutputStream("file.txt")); DataInputStream in = new DataInputStream(new FileInputStream("file.txt")) ) { out.writeUTF("wikiHow is a great place to learn"); out.writeBoolean(true); out.writeInt(10430); out.writeDouble(20.9d); out.writeFloat(23.10f); System.out.println(in.readUTF()); System.out.println(in.readBoolean()); System.out.println(in.readInt()); System.out.println(in.readDouble()); System.out.println(in.readFloat()); } catch (IOException e) { e.printStackTrace(); } }
- 8Run the program. Data is written to the
file.txtand then read and printed to the console.wikiHow is a great place to learn true 10430 20.9 23.1
Method Four of Four: Using Object Streams
Object streams handle binary input and output of Java objects. Like data streams, object streams make it very easy to read and write primitive data types and Strings, but also any object that implementsSerializableinterface. Most common usage of object streams is in network applications where both server and client are written in Java.- 1Create a serializable class. Create a class that implements
Serializableinterface. Name the class however you'd like, but in this article we will name it WikiHowian.public class WikiHowian implements Serializable { }
- 2Create a few private (serializable) variables. Since
WikiHowianclass represents a person, we will create two String variables for first and last name and anintvariable for age.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; }
- 3Create a constructor. The constructor will contain
firstName,secondNameandageparameters, corresponding to theprivatevariable types.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } }
- 4Override
toStringmethod. OverridingtoStringwill, later on, allow us to print the object to the console easily.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } }
- 5Create a main method. You can add throws IOException, ClassNotFoundException declaration to the method signature to avoid adding the catch block to the try-with-resources block.
public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { } }
- 6Create a try-with-resources block.Try-with-resources block will automatically close streams for us.
public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try () { } } }
- 7Create
ObjectOutputStreamin the block statement. In the constructor of the created input stream, createFileOutputStreamand specify an arbitrary file name inside its constructor. In this article, we will name it file.txt.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt"))) { } } }
- 8Create
ObjectInputStreamin the block statement. In the constructor of the created input stream, create aFileInputStreamand specify file name from the previous step inside its constructor. In this article, we named it file.txt.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt")); ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt")) ) { } } }
- 9Instantiate the previously created serializable class. Choose first name, last name and age arbitrarily.
public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt")); ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt")) ) { WikiHowian wikiHowian = new WikiHowian("John", "Doe", 23); } } }
- 10Write object to the output stream.Exactly, you can write the complete object to the output stream. The object, as it implements
Serializableinterface, is serialized into ones and zeroes, and stored in the file.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt")); ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt")) ) { WikiHowian wikiHowian = new WikiHowian("John", "Doe", 23); out.writeObject(wikiHowian); } } }
- 11Read object from the input stream and print it. Same way the object was written to a file, we read it from the file and, thanks to overriding
toStringmethod, easily print it to the console.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt")); ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt")) ) { WikiHowian wikiHowian = new WikiHowian("John", "Doe", 23); out.writeObject(wikiHowian); System.out.println(in.readObject()); } } }
- 12Catch and handle IOException and ClassNotFoundException. Add a catch block to the try-with-resources block, catch
IOExceptionandClassNotFoundException. In case of an error, print the stack trace to the console.public class WikiHowian implements Serializable { private String firstName, lastName; private int age; public WikiHowian(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { return firstName + " " + lastName + ", " + age; } public static void main(String[] args) { try ( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt")); ObjectInputStream in = new ObjectInputStream(new FileInputStream("file.txt")) ) { WikiHowian wikiHowian = new WikiHowian("John", "Doe", 23); out.writeObject(wikiHowian); System.out.println(in.readObject()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
- 13Run the program. Object is transformed (serialized) into ones and zeroes, and written to a file. Afterwards, ones and zeroes are read and constructed back into an object.
John Doe, 23
- If you created
thanks for the info. Where did you learn programming in java?
TumugonBurahinI just learned in school with you haha. By the way programming is fun and has logic.
Burahin