java tutorial - Java I/O streams and working with files and directories - java tutorial - java programming - learn java - java basics - java for beginners



  • The java.io package contains every class to perform input and output in Java.
  • All streams are represented by the input stream and the output address.

Streams

The flows in Java are defined as a sequence of data. There are two types of threads:

  • InPutStream - the input stream is used to read data from the source.
  • OutPutStream - the output stream is used to write data to the destination.

Java provides strong but flexible support for I / O associated with files and networks, but this guide covers only the basic functions associated with threads and I / O. Let's consider the most common examples in the following order.

Byte stream

Byte streams in Java are used to implement the input and output of 8-bit bytes. Despite the many classes associated with byte streams, the most common use is the following classes: FileInputStream and FileOutputStream. Below is an example illustrating the use of the data of two classes for copying from one file to another.

  • Note by example: to copy a file, you must create a file file.txt in the project folder with any or empty content.

Sample Code

import java.io.*;
public class FileCopy {

   public static void main(String args[]) throws IOException {  
      FileInputStream fileIn = null;
      FileOutputStream fileOut = null;

      try {
         fileIn = new FileInputStream("file.txt");
         fileOut = new FileOutputStream("copied_file.txt");
         
         int a;
	// Copy the contents of file.txt
         while ((a = fileIn.read()) != -1) {
            fileOut.write(a); // Read the contents of the file file.txt and write to the file copied_file.txt
         }
      }finally {
         if (fileIn != null) {
            fileIn.close();
         }
         if (fileOut != null) {
            fileOut.close();
         }
      }
   }
}
click below button to copy the code. By - java tutorial - team

Now consider the file file.txt with the following content:

The contents of file.txt

As a next step, you need to compile the java program and execute it, which will create a copied_file.txt file with the same contents as file.txt. Thus, we place the designated code in FileCopy.java and perform the following action:


$javac FileCopy.java
$java FileCopy
click below button to copy the code. By - java tutorial - team

Character Flows

  • Byte streams in Java allow the input and output of 8-bit bytes, while character streams are used to input and output 16-bit Unicode.
  • Despite the many classes associated with symbol streams, the most common use is the following classes: FileReader and FileWriter.
  • Despite the fact that the internal FileReader uses FileInputStream, and FileWriter uses FileOutputStream, the main difference is that FileReader reads two bytes at a particular time, while FileWriter writes two bytes at the same time.
  • We can reformulate the example above, in which two data classes are used to copy an input file (with Unicode characters) to an output file.

Example: to copy a file, you must create a file file.txt in the project folder with any or empty content.

Sample Code

import java.io.*;
public class FileCopy {

   public static void main(String args[]) throws IOException {
      FileReader fileIn = null;
      FileWriter fileOut = null;

      try {
         fileIn = new FileReader("file.txt");
         fileOut = new FileWriter("copied_file.txt");
         
         int a;
         while ((a = fileIn.read()) != -1) {
            fileOut.write(a);
         }
      } finally {
         if (fileIn != null) {
            fileIn.close();
         }
         if (fileOut != null) {
            fileOut.close();
         }
      }
   }
}
click below button to copy the code. By - java tutorial - team

Now consider the file file.txt with the following content:

The contents of file.txt
click below button to copy the code. By - java tutorial - team

As a next step, you need to compile the program and execute it, which will create a copied_file.txt file with the same contents as file.txt. Thus, we place the designated code in FileCopy.java and perform the following action:

$javac FileCopy.java
$java FileCopy
click below button to copy the code. By - java tutorial - team

Standard Threads

  • All programming languages..provide support for standard input / output, where the user program can make input via the keyboard and output to the computer screen.
  • If you are familiar with C or C ++ programming languages, you should be aware of three standard STDIN devices , STDOUT and STDERR. Similarly, Java provides the following three standard streams:
    • Standard input - used to transfer data to the user program, the keyboard is usually used as a standard input stream, represented in the form of System.in.
    • Standard output is to output the data received in the user program, and usually the screen The computer is used as a standard output stream, represented as System.out.
    • Standard error - used to display error data from the user program, most often the computer screen serves as a standard th error message stream, represented as System.err.
  • Below is a sample program for reading the standard input stream, before the user enters "q".

Sample Code

import java.io.*;
public class ReadConsole {

   public static void main(String args[]) throws IOException {
      InputStreamReader inStRe = null;

      try {
         inStRe = new InputStreamReader(System.in);
         System.out.println("Enter the characters, the 'q' character to exit.");
         char a;
         do {
            a = (char) inStRe.read();
            System.out.print(a);
         } while(a != 'q');
      }finally {
         if (inStRe != null) {
            inStRe.close();
         }
      }
   }
}
click below button to copy the code. By - java tutorial - team
  • We place the above code in the ReadConsole.java file and try to compile and execute how it is presented in the next program. This program continues to read and print the same character before pressing 'q':

Reading and writing a file

  • As indicated above, the stream is a sequence of data. The InputStream is used to read data from the source, OutputStream serves to write data to the destination.

The following is a class hierarchy for managing I / O flows.

In this lesson we will consider two important threads: FileInputStream and FileOutputStream.

Flow FileInputStream - read from file

  • The FileInputStream is a stream that is used by Java to read data from a file. Objects can be created using the new keyword, several types of constructors are available.
  • The represented constructor uses the file name as the stream to create an input stream object to read the file:
InputStream a = new FileInputStream("D:/myprogramm/java/test");
click below button to copy the code. By - java tutorial - team
  • The constructor below uses an object file to create an input stream object to read the file. First, we create an object file using the File () method as follows:
File a = new File("D:/myprogramm/java/test");
InputStream a = new FileInputStream(a);
click below button to copy the code. By - java tutorial - team
  • Now, having received the InputStream object, you should familiarize yourself with the following list of auxiliary methods that can be used to read the stream or perform other operations in the stream.
No. Method and Description
1 public void close () throws IOException {}
This method closes the output file stream in Java and returns an IOException.
2 protected void finalize () throws IOException {}
This method cleans up the connection to the file. Allows you to closed method of this output file stream and returns an IOException.
3 public int read (int r) throws IOException {}
This method performs in Java the reading of specified bytes of data from the InputStream. Return data of type int. Return the next byte of data, at the end of the file will be returned to -1.
4 public int read (byte [] r) throws IOException {}
This method reads the bytes r.length from the input stream to an array. Returns the total number of bytes read. At the end of the file, a return to -1 will be made.
5 public int () throws IOException {}
Returns the number of bytes that can be read from the input file stream. Returning data of type int.

There are also other available output streams, more detailed information about which is provided by the following links:

  • ByteArrayOutputStream
  • DataOutputStream

Sample Code

  • The following Example shows InputStream and OutputStream - the streams for reading, creating and writing the file:
import java.io.*;
public class File {

   public static void main(String args[]) {
   
      try {
         char c[] = {'a','b','c'};
         OutputStream output = new FileOutputStream("file.txt"); // Create a text file
         for(int i = 0; i < c.length; i++) {
            output.write(c[i]); // Write each character in a text file
         }
         output.close();
     
         InputStream input = new FileInputStream("file.txt");
         int size = input.available();

         for(int j = 0; j < size; j++) {
            System.out.print((char)input.read() + " "); // Read the text file character by character
         }
         input.close();
      }catch(IOException e) {
         System.out.print("Exception");
      }	
   }
}
click below button to copy the code. By - java tutorial - team
  • The above java code will create a file file.txt and will write the specified characters in char format. The same will be displayed on the standard output screen.

Navigating the file system and I / O

There are a number of other classes that we have to consider in order to familiarize ourselves with the basics of navigation in the file system and I / O.

  • File Class
  • FileReader Class
  • FileWriter Class

Catalogs in Java

  • The Java directory is represented by a File that can contain a list of other files and directories.
  • Using the File object, you can create a directory, scroll through the list of files represented in the directory.
  • For more detailed information, see the list of all methods that can be called from the File object, being associated with directories.

Creating directories

There are two utility File methods that can be used to create directories:

  • The mkdir () method allows you to create a folder in Java, returning true when the operation succeeds, and false in the event of a failure. A failure indicates that the path specified in the File object already exists, or that the directory can not be created due to the fact that the full path does not yet exist.
  • The mkdirs () method creates a directory and all the parent directories .

The following Example shows the creation of the folder "/java/wikitechy/newdir":

Sample Code

import java.io.File;
public class CreateDirectory {

   public static void main(String args[]) {
      String nameDir = "/java/wikitechy/newdir";
      File a = new File(nameDir);
      
    // Create a folder on the disk and all the upstream directories
      a.mkdirs();
   }
}
click below button to copy the code. By - java tutorial - team

Compile and run the following code to create the directory "/java/wikitechy/newdir". Note:Java automatically generates path separators on UNIX and Windows with regard to conventions. If you use a slash (/) while working with Java on a Windows system, the path is correctly resolved.

List of files in the folder

  • The list () method represented by the File object can be used to provide a list of all the files and directories in the specified folder in the following form:

Sample Code

import java.io.File;
public class ReadDirectory {

   public static void main(String[] args) {
      File pathDir = null;
      String[] pathsFilesAndDir;
  
      try {      
        // Create a new file
         pathDir = new File("/NetBeans 8.2/Projects/ReadDirectory/ReadDirectory/"); // There must be a specified directory on the disk, otherwise the program will generate an error

         // Array of files and folders
         pathsFilesAndDir = pathDir.list();

         for(String path:pathsFilesAndDir) {
          // List files and directories
            System.out.println(path);
         }
      }catch(Exception e) {
        // If an error occurred
         e.printStackTrace();
      }
   } 
}
click below button to copy the code. By - java tutorial - team

The result, based on the directories and files available in your/NetBeans directory 8.2/Projects/ReadDirectory/ReadDirectory /:

build
build.xml
manifest.mf
nbproject
src
ReadDirectory

Related Searches to Java I/O streams and working with files and directories