Author: saqibkhan

  • FileInputStream 

    Introduction

    The Java.io.FileInputStream class obtains input bytes from a file in a file system. What files are available depends on the host environment. Following are the important points about FileInputStream −

    • This class is meant for reading streams of raw bytes such as image data.
    • For reading streams of characters, use FileReader.

    Class declaration

    Following is the declaration for Java.io.FileInputStream class −

    public class FileInputStream
       extends InputStream
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class constructors

    Sr.No.Constructor & Description
    1FileInputStream(File file)This creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
    2FileInputStream(FileDescriptor fdObj)This creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
    3FileInputStream(String name)This creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

    Class methods

    Sr.No.Method & Description
    1int available()This method returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
    2void close()This method closes this file input stream and releases any system resources associated with the stream.
    3protected void finalize()This method ensures that the close method of this file input stream is called when there are no more references to it.
    4FileChannel getChannel()This method returns the unique FileChannel object associated with this file input stream.
    5FileDescriptor getFD()This method returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
    6int read()This method reads a byte of data from this input stream.
    7int read(byte[] b)This method reads up to b.length bytes of data from this input stream into an array of bytes.
    8int read(byte[] b, int off, int len)This method reads up to len bytes of data from this input stream into an array of bytes.
    9long skip(long n)This method skips over and discards n bytes of data from the input stream.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.InputStream
    • Java.io.Object
  • FileDescriptor 

    Introduction

    The Java.io.FileDescriptor class instances serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. Following are the important points about FileDescriptor −

    • The main practical use for a file descriptor is to create a FileInputStream or FileOutputStream to contain it.
    • Applications should not create their own file descriptors.

    Class declaration

    Following is the declaration for Java.io.FileDescriptor class −

    public final class FileDescriptor
       extends Object
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for Java.io.FileDescriptor class −

    • static FileDescriptor err − This is the handle to the standard error stream.
    • static FileDescriptor in − This is the handle to the standard input stream.
    • static FileDescriptor out − This is the handle to the standard output stream.

    Class constructors

    Sr.No.Constructor & Description
    1FileDescriptor()This method constructs an (invalid) FileDescriptor object.

    Class methods

    Sr.No.Method & Description
    1void sync()This method force all system buffers to synchronize with the underlying device.
    2boolean valid()This method tests if this file descriptor object is valid.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.Object
  • Java – File Class

    Java File Class

    Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion, etc.

    The File object represents the actual file/directory on the disk.

    File Class Constructors

    Following is the list of constructors to create a File object.

    Sr.No.Method & Description
    1File(File parent, String child)This constructor creates a new File instance from a parent abstract pathname and a child pathname string.
    2File(String pathname)This constructor creates a new File instance by converting the given pathname string into an abstract pathname.
    3File(String parent, String child)This constructor creates a new File instance from a parent pathname string and a child pathname string.
    4File(URI uri)This constructor creates a new File instance by converting the given file: URI into an abstract pathname.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    File Class Methods

    Once you have File object in hand, then there is a list of helper methods which can be used to manipulate the files.

    Sr.No.Method & Description
    1public String getName()Returns the name of the file or directory denoted by this abstract pathname.
    2public String getParent()Returns the pathname string of this abstract pathname’s parent, or null if this pathname does not name a parent directory.
    3public File getParentFile()Returns the abstract pathname of this abstract pathname’s parent, or null if this pathname does not name a parent directory.
    4public String getPath()Converts this abstract pathname into a pathname string.
    5public boolean isAbsolute()Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise.
    6public String getAbsolutePath()Returns the absolute pathname string of this abstract pathname.
    7public boolean canRead()Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise.
    8public boolean canWrite()Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
    9public boolean exists()Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.
    10public boolean isDirectory()Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise.
    11public boolean isFile()Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise.
    12public long lastModified()Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
    13public long length()Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
    14public boolean createNewFile() throws IOExceptionAtomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists.
    15public boolean delete()Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise.
    16public void deleteOnExit()Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
    17public String[] list()Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
    18public String[] list(FilenameFilter filter)Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
    20public File[] listFiles()Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
    21public File[] listFiles(FileFilter filter)Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
    22public boolean mkdir()Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise.
    23public boolean mkdirs()Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise.
    24public boolean renameTo(File dest)Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise.
    25public boolean setLastModified(long time)Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise.
    26public boolean setReadOnly()Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise.
    27public static File createTempFile(String prefix, String suffix, File directory) throws IOExceptionCreates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. Returns an abstract pathname denoting a newly-created empty file.
    28public static File createTempFile(String prefix, String suffix) throws IOExceptionCreates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. Invoking this method is equivalent to invoking createTempFile(prefix, suffix, null). Returns abstract pathname denoting a newly-created empty file.
    29public int compareTo(File pathname)Compares two abstract pathnames lexicographically. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
    30public int compareTo(Object o)Compares this abstract pathname to another object. Returns zero if the argument is equal to this abstract pathname, a value less than zero if this abstract pathname is lexicographically less than the argument, or a value greater than zero if this abstract pathname is lexicographically greater than the argument.
    31public boolean equals(Object obj)Tests this abstract pathname for equality with the given object. Returns true if and only if the argument is not null and is an abstract pathname that denotes the same file or directory as this abstract pathname.
    32public String toString()Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.

    File Class Example in Java

    Following is an example to demonstrate File object −

    Open Compiler

    packagecom.tutorialspoint;importjava.io.File;publicclassFileDemo{publicstaticvoidmain(String[] args){File f =null;String[] strs ={"test1.txt","test2.txt"};try{// for each string in string array for(String s:strs ){// create new file
    
            f =newFile(s);// true if the file is executableboolean bool = f.canExecute();// find the absolute pathString a = f.getAbsolutePath();// prints absolute pathSystem.out.print(a);// printsSystem.out.println(" is executable: "+ bool);}}catch(Exception e){// if any I/O error occurs
         e.printStackTrace();}}}</code></pre>

    Consider there is an executable file test1.txt and another file test2.txt is non executable in the current directory. Let us compile and run the above program, This will produce the following result −

    Output

    /home/cg/root/2880380/test1.txt is executable: false
    /home/cg/root/2880380/test2.txt is executable: false
    
  • DataOutputStream 

    Introduction

    The Java.io.DataOutputStream class lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

    Class declaration

    Following is the declaration for Java.io.DataOutputStream class −

    public class DataOutputStream
       extends FilterOutputStream
    
      implements DataOutput

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for Java.io.DataOutputStream class −

    • protected int written − This is the number of bytes written to the data output stream so far.
    • protected OutputStream out − This is the underlying output stream to be filtered.

    Class constructors

    Sr.No.Constructor & Description
    1DataOutputStream(OutputStream out)This creates a new data output stream to write data to the specified underlying output stream.

    Class methods

    Sr.No.Method & Description
    1void flush()This method flushes this data output stream.
    2int size()This method returns the current value of the counter written, the number of bytes written to this data output stream so far.
    3void write(byte[] b, int off, int len)This method writes len bytes from the specified byte array starting at offset off to the underlying output stream.
    4void write(int b)This method writes the specified byte (the low eight bits of the argument b) to the underlying output stream.
    5void writeBoolean(boolean v)This method writes a boolean to the underlying output stream as a 1-byte value.
    6void writeByte(int v)This method writes out a byte to the underlying output stream as a 1-byte value.
    7void writeBytes(String s)This method writes out the string to the underlying output stream as a sequence of bytes.
    8void writeChar(int v)This method writes a char to the underlying output stream as a 2-byte value, high byte first.
    9void writeChars(String s)This method writes a string to the underlying output stream as a sequence of characters.
    10void writeDouble(double v)This method converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.
    11void writeFloat(float v)This method converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.
    12void writeInt(int v)This method writes an int to the underlying output stream as four bytes, high byte first.
    13void writeLong(long v)This method writes a long to the underlying output stream as eight bytes, high byte first.
    14void writeShort(int v)This method writes a short to the underlying output stream as two bytes, high byte first.
    15void writeUTF(String str)This method writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.FilterOutputStream
    • Java.io.Object
    • Java.io.DataOutput
  • DataInputStream 

    Introduction

    The Java.io.DataInputStream class lets an application read primitive Java data types from an underlying input stream in a machine-independent way.Following are the important points about DataInputStream −

    • An application uses a data output stream to write data that can later be read by a data input stream.
    • DataInputStream is not necessarily safe for multithreaded access. Thread safety is optional and is the responsibility of users of methods in this class.

    Class declaration

    Following is the declaration for Java.io.DataInputStream class −

    public class DataInputStream
       extends FilterInputStream
    
      implements DataInput

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for Java.io.DataInputStream class −

    • protected InputStream in − This is the input stream to be filtered.

    Class constructors

    Sr.No.Constructor & Description
    1DataInputStream(InputStream in)This creates a DataInputStream that uses the specified underlying InputStream.

    Class methods

    Sr.No.Method & Description
    1int read(byte[] b)This method reads some number of bytes from the contained input stream and stores them into the buffer array b
    2int read(byte[] b, int off, int len)This method reads up to len bytes of data from the contained input stream into an array of bytes.
    3boolean readBoolean()This method reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
    4byte readByte()This method reads and returns one input byte.
    5char readChar()This method reads two input bytes and returns a char value.
    6double readDouble()This method reads eight input bytes and returns a double value.
    7float readFloat()This method reads four input bytes and returns a float value.
    8void readFully(byte[] b)This method reads some bytes from an input stream and stores them into the buffer array b.
    9void readFully(byte[] b, int off, int len)This method reads len bytes from an input stream.
    10int readInt()This method reads four input bytes and returns an int value.
    11long readLong()This method reads eight input bytes and returns a long value.
    12short readShort()This method reads two input bytes and returns a short value.
    13int readUnsignedByte()This method reads one input byte, zero-extends it to type int, and returns the result, which is therefore in the range 0 through 255.
    14int readUnsignedShort()This method reads two input bytes and returns an int value in the range 0 through 65535.
    15String readUTF()This method reads in a string that has been encoded using a modified UTF-8 format.
    16static String readUTF(DataInput in)This method reads from the stream in a representation of a Unicode character string encoded in modified UTF-8 format; this string of characters is then returned as a String.
    17int skipBytes(int n)This method makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.FilterInputStream
    • Java.io.Object
  • Console 

    Introduction

    The Java.io.Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine.

    Class declaration

    Following is the declaration for Java.io.Console class −

    public final class Console
       extends Object
    
      implements Flushable

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.No.Method & Description
    1void flush()This method flushes the console and forces any buffered output to be written immediately.
    2Console format(String fmt, Object… args)This method writes a formatted string to this console’s output stream using the specified format string and arguments.
    3Console printf(String format, Object… args)This method is used to write a formatted string to this console’s output stream using the specified format string and arguments.
    4Reader reader()This method retrieves the unique Reader object associated with this console.
    5String readLine()This method reads a single line of text from the console.
    6String readLine(String fmt, Object… args)This method provides a formatted prompt, then reads a single line of text from the console.
    7char[] readPassword()This method reads a password or passphrase from the console with echoing disabled.
    8char[] readPassword(String fmt, Object… args)This method provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.
    9PrintWriter writer()This method retrieves the unique PrintWriter object associated with this console.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.Object
  • CharArrayWriter 

    Introduction

    The Java.io.CharArrayWriter class implements a character buffer that can be used as an Writer. The buffer automatically grows when data is written to the stream.

    Class declaration

    Following is the declaration for Java.io.CharArrayWriter class −

    public class CharArrayWriter
       extends Writer
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for Java.io.CharArrayWriter class −

    • protected char[] buf − This is the buffer where data is stored.
    • protected int count − This is the number of chars in the buffer.
    • protected Object lock − This is the object used to synchronize operations on this stream.

    Class constructors

    Sr.No.Constructor & Description
    1CharArrayWriter()This creates a CharArrayReader from the specified array of chars.
    2CharArrayWriter(int initialSize)This creates a new CharArrayWriter with the specified initial size.

    Class methods

    Sr.No.Method & Description
    1CharArrayWriter append(char c)This method appends the specified character to this writer.
    2CharArrayWriter append(CharSequence csq)This method appends the specified character sequence to this writer.
    3CharArrayWriter append(CharSequence csq, int start, int end)This method appends a subsequence of the specified character sequence to this writer.
    4void close()This method close the stream.
    5void flush()This method flush the stream.
    6void reset()This method resets the buffer so that you can use it again without throwing away the already allocated buffer.
    7int size()This method returns the current size of the buffer.
    8char[] toCharArray()This method returns a copy of the input data.
    9String toString()This method converts input data to a string.
    10void write(char[] c, int off, int len)This method writes characters to the buffer.
    11void write(int c)This method writes a character to the buffer.
    12void write(String str, int off, int len)This method write a portion of a string to the buffer.
    13void writeTo(Writer out)This method writes the contents of the buffer to another character stream.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.Writer
    • Java.io.Object
  • CharArrayReader 

    Introduction

    The Java.io.CharArrayReader class implements a character buffer that can be used as a character-input stream.

    Class declaration

    Following is the declaration for Java.io.CharArrayReader class −

    public class CharArrayReader
       extends Reader
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for Java.io.CharArrayReader class −

    • protected char[] buf − This is the character buffer.
    • protected int count − This is the index of the end of this buffer.
    • protected int markedPos − This is the position of mark in buffer.
    • protected int pos − This is the current buffer position.
    • protected Object lock − This is the object used to synchronize operations on this stream.

    Class constructors

    Sr.No.Constructor & Description
    1CharArrayReader(char[] buf)This creates a CharArrayReader from the specified array of chars.
    2CharArrayReader(char[] buf, int offset, int length)This creates a CharArrayReader from the specified array of chars.

    Class methods

    Sr.No.Method & Description
    1void close()This method closes the stream and releases any system resources associated with it.
    2void mark(int readAheadLimit)This method marks the present position in the stream.
    3boolean markSupported()This method tells whether this stream supports the mark() operation, which it does.
    4int read()This method reads a single character.
    5int read(char[] b, int off, int len)This method Reads characters into a portion of an array.
    6boolean ready()This method tells whether this stream is ready to be read.
    7void reset()This method resets the stream to the most recent mark, or to the beginning if it has never been marked.
    8long skip(long n)This method skips characters.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.Reader
    • Java.io.Object
  • ByteArrayOutputStream 

    Introduction

    The Java.io.ByteArrayOutputStream class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.Following are the important points about ByteArrayOutputStream −

    • Closing a ByteArrayOutputStream has no effect.
    • The methods in this class can be called after the stream has been closed without generating an IOException.

    Class declaration

    Following is the declaration for Java.io.ByteArrayOutputStream class −

    public class ByteArrayOutputStream
       extends OutputStream
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for Java.io.ByteArrayOutputStream class −

    • protected byte[] buf − This is the buffer where data is stored.
    • protected int count − This is the number of valid bytes in the buffer.

    Class constructors

    Sr.No.Constructor & Description
    1ByteArrayOutputStream()This creates a new byte array output stream.
    2ByteArrayOutputStream(int size)This creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

    Class methods

    Sr.No.Method & Description
    1void close()Closing a ByteArrayOutputStream has no effect.
    2void reset()This method resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded.
    3int size()This method returns the current size of the buffer.
    4byte[] toByteArray()This method creates a newly allocated byte array.
    5String toString()This method converts the buffer’s contents into a string decoding bytes using the platform’s default character set.
    6String toString(String charsetName)This method converts the buffer’s contents into a string by decoding the bytes using the specified charsetName.
    7void write(byte[] b, int off, int len)This method writes len bytes from the specified byte array starting at offset off to this byte array output stream.
    8void write(int b)This method Writes the specified byte to this byte array output stream.
    9void writeTo(OutputStream out)This method writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream’s write method using out.write(buf, 0, count).

    Methods inherited

    This class inherits methods from the following classes −

    • Java.io.OutputStream
    • Java.io.Object
  • ByteArrayInputStream 

    Introduction

    The java.io.ByteArrayInputStream class contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.Following are the important points about ByteArrayInputStream −

    • Closing a ByteArrayInputStream has no effect.
    • The methods in this class can be called after the stream has been closed without generating an IOException.

    Class declaration

    Following is the declaration for java.io.ByteArrayInputStream class −

    public class ByteArrayInputStream
       extends InputStream
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for java.io.ByteArrayInputStream class −

    • protected byte[] buf − This is an array of bytes that was provided by the creator of the stream.
    • protected int count − This is the index one greater than the last valid character in the input stream buffer.
    • protected int mark − This is the currently marked position in the stream.
    • protected int pos − This is the index of the next character to read from the input stream buffer.

    Class constructors

    Sr.No.Constructor & Description
    1ByteArrayInputStream(byte[] buf)This creates a ByteArrayInputStream so that it uses buf as its buffer array.
    2ByteArrayInputStream(byte[] buf, int offset, int length)This creates ByteArrayInputStream that uses buf as its buffer array.

    Class methods

    Sr.No.Method & Description
    1int available()This method returns the number of remaining bytes that can be read (or skipped over) from this input stream.
    2void close()Closing a ByteArrayInputStream has no effect.
    3void mark(int readAheadLimit)This method set the current marked position in the stream.
    4boolean markSupported()This method tests if this InputStream supports mark/reset.
    5int read()This method reads the next byte of data from this input stream.
    6int read(byte[] b, int off, int len)This method reads up to len bytes of data into an array of bytes from this input stream.
    7void reset()This method resets the buffer to the marked position.
    8long skip(long n)This method skips n bytes of input from this input stream.

    Methods inherited

    This class inherits methods from the following classes −

    • java.io.InputStream
    • java.io.Object