How to Use I/O Streams in Java

Method 1 of 4:

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.

  1. How to Use I/O Streams in Java Picture 1
    Create 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.
  2. How to Use I/O Streams in Java Picture 2
    Create 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) { } 
  3. How to Use I/O Streams in Java Picture 3
    Create a try-with-resources block. Try-with-resources block will automatically close streams for us.
    public static void main(String[] args) { try () { } } 
  4. How to Use I/O Streams in Java Picture 4
    Create FileInputStream or FileReader in 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")) { } } 
    1. The former is a byte stream, the latter is a character stream.
  5. How to Use I/O Streams in Java Picture 5
    Create FileOutputStream or FileWriter in 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") ) { } } 
    1. If you created FileInputStream, you need to create FileOutputStream. The same goes for the FileReader and FileWriter.
  6. How to Use I/O Streams in Java Picture 6
    Create int variable. 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; } } 
  7. How to Use I/O Streams in Java Picture 7
    Read data from input stream. Create a while loop in which the data is read into the previously created int variable 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) { } } } 
  8. How to Use I/O Streams in Java Picture 8
    Write 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); } } } 
  9. How to Use I/O Streams in Java Picture 9
    Catch and handle IOException. Add a catch block to the try-with-resources block, catch IOException and, 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(); } } 
  10. How to Use I/O Streams in Java Picture 10
    Run the program. Contents of the file.txt are copied to the file-copy.txt which, if it doesn't exist yet, is created.
Method 2 of 4:

Using Buffered Streams

Buffered 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.

  1. How to Use I/O Streams in Java Picture 11
    Create 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.
  2. How to Use I/O Streams in Java Picture 12
    Create 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) { } 
  3. How to Use I/O Streams in Java Picture 13
    Create a try-with-resources block. Try-with-resources block will automatically close streams for us.
    public static void main(String[] args) { try () { } } 
  4. How to Use I/O Streams in Java Picture 14
    Create BufferedReader in the block statement. In the constructor of the created input stream, create a FileReader and 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"))) { } } 
  5. How to Use I/O Streams in Java Picture 15
    Create BufferedWriter in the block statement. In the constructor of the created output stream, create a FileWriter and 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")) ) { } } 
  6. How to Use I/O Streams in Java Picture 16
    Create String variable. 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; } } 
  7. How to Use I/O Streams in Java Picture 17
    Read lines from input stream. Create a while loop in which the lines are read into the previously created String variable until it reads null. 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) { } } } 
  8. How to Use I/O Streams in Java Picture 18
    Write 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. BufferedReader reads 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()); } } } 
  9. How to Use I/O Streams in Java Picture 19
    Catch and handle IOException. Add a catch block to the try-with-resources block, catch IOException and, 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(); } } 
  10. How to Use I/O Streams in Java Picture 20
    Run the program. Contents of the file.txt are copied to the file-copy.txt which, if it doesn't exist yet, is created.
Method 3 of 4:

Using Data Streams

Data streams handle binary input and output of primitive data types and Strings. Data streams make it very easy to read and write boolean, char, byte, short, int, long, float, double and String values. Most common usage of data streams is in network applications (e.g. instant messengers).

  1. How to Use I/O Streams in Java Picture 21
    Create 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) { } 
  2. How to Use I/O Streams in Java Picture 22
    Create a try-with-resources block. Try-with-resources block will automatically close streams for us.
    public static void main(String[] args) { try () { } } 
  3. How to Use I/O Streams in Java Picture 23
    Create DataOutputStream in the block statement. In the constructor of the created input stream, create FileOutputStream and 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"))) { } } 
  4. How to Use I/O Streams in Java Picture 24
    Create DataInputStream in the block statement. In the constructor of the created input stream, create a FileInputStream and 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")) ) { } } 
  5. How to Use I/O Streams in Java Picture 25
    Write some data to the output stream. In the body of the try-with-resources block, write String, boolean, int and 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); } } 
  6. How to Use I/O Streams in Java Picture 26
    Read 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()); } } 
  7. How to Use I/O Streams in Java Picture 27
    Catch and handle IOException. Add a catch block to the try-with-resources block, catch IOException and, 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(); } } 
  8. How to Use I/O Streams in Java Picture 28
    Run the program. Data is written to the file.txt and then read and printed to the console.
    wikiHow is a great place to learn true 10430 20.9 23.1 
Method 4 of 4:

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 implements Serializable interface. Most common usage of object streams is in network applications where both server and client are written in Java.

  1. How to Use I/O Streams in Java Picture 29
    Create a serializable class. Create a class that implements Serializable interface. Name the class however you'd like, but in this article we will name it WikiHowian.
    public class WikiHowian implements Serializable { } 
  2. How to Use I/O Streams in Java Picture 30
    Create a few private (serializable) variables. Since WikiHowian class represents a person, we will create two String variables for first and last name and an int variable for age.
    public class WikiHowian implements Serializable { private String firstName, lastName; private int age; } 
  3. How to Use I/O Streams in Java Picture 31
    Create a constructor. The constructor will contain firstName, secondName and age parameters, corresponding to the private variable 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; } } 
  4. How to Use I/O Streams in Java Picture 32
    Override toString method. Overriding toString will, 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; } } 
  5. How to Use I/O Streams in Java Picture 33
    Create 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) { } } 
  6. How to Use I/O Streams in Java Picture 34
    Create 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 () { } } } 
  7. How to Use I/O Streams in Java Picture 35
    Create ObjectOutputStream in the block statement. In the constructor of the created input stream, create FileOutputStream and 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"))) { } } } 
  8. How to Use I/O Streams in Java Picture 36
    Create ObjectInputStream in the block statement. In the constructor of the created input stream, create a FileInputStream and specify file name from the previous step inside its constructor. In this article, we named it file.txt.
    public class WikiHowian implements Serializable { 
    5 ★ | 1 Vote

    May be interested

    • What is the difference between Go and Java?What is the difference between Go and Java?
      is golang better than java? is golang harder than java? can golang replace java? this comparison will give you the answer.
    • How to Fix JavaHow to Fix Java
      java is a computing platform that allows you to play games and view videos on your computer. you can tell that your computer is having problems with java if you see java errors appear when you try to run a program or visit a website that...
    • How to Compile a Java ProgramHow to Compile a Java Program
      this wikihow teaches you how to turn your java source code into an executable app using a local and online compiler. if you're using a computer, the most common way to compile java code is using java software development kit (java sdk)...
    • Oracle wants to turn Java EE into fully open sourceOracle wants to turn Java EE into fully open source
      this week, oracle announced plans to move java ee project management to an open source platform, like apache or eclipse.
    • Write and run Java code on the computer for the first timeWrite and run Java code on the computer for the first time
      after you've installed java and set up a path on your computer, you need to know how to run a simple java code on your computer. in this article, we will try to write the first java program, as well as the commands to run this program in cmd.
    • Download Java Runtime Environment 8-build-251Download Java Runtime Environment 8-build-251
      java runtime environment (jre) is a software class that provides the services needed to execute java applications. it is an essential component of the java development kit (jdk) and contains all the tools needed to run various java-based software programs.
    • How to Enable JavaHow to Enable Java
      java is a programming language and platform commonly used in a number of websites and applications. when java is not enabled, you can experience difficulty with viewing or using certain websites and applications. to use java, you must have...
    • 200 common Java interview questions, with reference answers200 common Java interview questions, with reference answers
      if you are going to a java interview, preparing for java programming language questions is necessary. these java interview questions are compiled from tutorialspoint and are accompanied by reference answers.
    • What is the difference between Java and JavaScript?What is the difference between Java and JavaScript?
      although the names of java and javascript seem to be related (javascript seems to be a script in java?), but that's the only similarity. these two languages ​​are not technically related to each other.
    • How to uninstall Java on MacHow to uninstall Java on Mac
      whether you're sick of java's security issues or find it unnecessary, there's a fairly easy way to uninstall java from your mac using java's installer.