The Java io package contains nearly every class you might ever need to perform input and output (I/O) in Java.
All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.
Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers very basic functionlity related to streams and I/O.
We would see most commonly used example one by one:
Reading Console Input:
Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream.
Here is most common syntax to obtain BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a string from the console.
Reading Characters from Console:
To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value.
It returns .1 when the end of the stream is encountered. As you can see, it can throw an IOException. The following program demonstrates read( ) by reading characters from the console until the user types a "q":
// Use a BufferedReader to read characters from the console.
import java.io.*;
public class BRRead
{
public static void main(String args[]) throws IOException
{
char c; // Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do
{
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run: Enter characters, 'q' to quit.
123abcq 1 2 3 a b c q Reading Strings from Console:
To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.
Its general form is shown here:
String readLine( ) throws IOException
The following program demonstrates BufferedReader and the readLine( ) method. T
he program reads and displays lines of text until you enter the word "end":
// Read a string from console using a BufferedReader.
import java.io.*;
public class BRReadLines
{
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
}
Here is a sample run: Enter lines of text. Enter 'end' to quit.
This is line one This is line one This is line two
This is line two end end Writing Console Output:
Console output is most easily accomplished with print( ) and println( ), described earlier.
These methods are defined by the class PrintStream which is the type of the object referenced bySystem.out.
Even though System.out is a byte stream, using it for simple program output is still acceptable.
Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ).
Thus, write( ) can be used to write to the console.
The simplest form of write( ) defined by PrintStream is shown here:
void write(int byteval)
This method writes to the stream the byte specified by byteval.
Although byteval is declared as an integer, only the low-order eight bits are written.
Example:
Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:
import java.io.*;
// Demonstrate System.out.write().
public class WriteDemo
{
public static void main(String args[])
{
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
This would produce simply 'A' character on the output screen. A
Note: You will not often use write( ) to perform console output because print( ) and println( ) are substantially easier to use. Reading and Writing Files: As described earlier, A stream can be defined as a sequence of data.
The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams.
The two important streams are FileInputStream and FileOutputStream which would be discussed in this tutorial:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file:
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file.
First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.
SN | Method | Description |
1 | public void close() throws IOException{} | This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. |
2 | protected void finalize()throws IOException {} | This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. |
3 | public int read(int r)throws IOException{} | This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's end of file. |
4 | public int read(byte[] r) throws IOException{} | This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned. |
5 | public int available() throws IOException{} | Gives the number of bytes that can be read from this file input stream. Returns an int. |
ByteArrayInputStream
The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream.
The input source is a byte array. There are following forms of constructors to create ByteArrayInputStream objects Takes a byte array as the parameter:
ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a);
Another form takes an array of bytes, and two ints, where off is the first byte to be read and len is the number of bytes to be read.
ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len)
Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream.
SN | Method | Description |
1 | public int read() | This method reads the next byte of data from the InputStream. Returns an int as the next byte of data. If it is end of file then it returns -1. |
2 | public int read(byte[] r, int off, int len) | This method reads upto len number of bytes starting from off from the input stream into an array. Returns the total number of bytes read. If end of file -1 will be returned. |
3 | public int available() | Gives the number of bytes that can be read from this file input stream. Returns an int that gives the number of bytes to be read. |
4 | public void mark(int read) | This sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid. |
5 | public long skip(long n) | Skips n number of bytes from the stream. |
Example:
Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream
import java.io.*;
public class ByteStreamTest
{
public static void main(String args[])throws IOException
{
ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 )
{
// Gets the inputs from the user
bOutput.write(System.in.read());
}
byte b [] = bOutput.toByteArray();
System.out.println("Print the content");
for(int x= 0 ; x < b.length; x++)
{
// printing the characters
System.out.print((char)b[x] + " ");
}
System.out.println(" ");
int c;
ByteArrayInputStream bInput = new ByteArrayInputStream(b);
System.out.println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ )
{
while(( c= bInput.read())!= -1)
{
System.out.println(Character.toUpperCase((char)c));
}
bInput.reset();
}
}
}
Here is the sample run of the above program:
asdfghjkly
Print the content
a s d f g h j k l y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y
DataInputStream
The DataInputStream is used in the context of DataOutputStream and can be used to read primitives.
Following is the constructor to create an InputStream:
InputStream in = DataInputStream(InputStream in);
Once you have DataInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream.
SN | Method | Description |
1 | public final int read(byte[] r, int off, int len)throws IOException | Reads up to len bytes of data from the input stream into an array of bytes. Returns the total number of bytes read into the buffer otherwise -1 if it is end of file. |
2 | Public final int read(byte [] b)throws IOException | Reads some bytes from the inputstream an stores in to the byte array. Returns the total number of bytes read into the buffer otherwise -1 if it is end of file. |
3 | (a) public final Boolean readBooolean()throws IOException, (b) public final byte readByte()throws IOException, (c) public final short readShort()throws IOException (d) public final Int readInt()throws IOException | These methods will read the bytes from the contained InputStream. Returns the next two bytes of the InputStream as the specific primitive type. |
4 | public String readLine() throws IOException | Reads the next line of text from the input stream. It reads successive bytes, converting each byte separately into a character, until it encounters a line terminator or end of file; the characters read are then returned as a String. |
Following is the example to demonstrate DataInputStream and DataInputStream.
This example reads 5 lines given in a file test.txt and convert those lines into capital letters and finally copies them into another file test1.txt.
import java.io.*;
public class Test
{
public static void main(String args[])throws IOException
{
DataInputStream d = new DataInputStream(new FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt"));
String count;
while((count = d.readLine()) != null)
{
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}
Here is the sample run of the above program:
THIS IS TEST 1 ,
THIS IS TEST 2 ,
THIS IS TEST 3 ,
THIS IS TEST 4 ,
THIS IS TEST 5 ,
FileOutputStream:
FileOutputStream is used to create a file and write data into it.The stream would create a file, if it doesn't already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object. Following constructor takes a file name as a string to create an input stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file.
First we create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand then there is a list of helper methods which can be used to write to stream or to do other operations on the stream.
SN Methods with Description 1 public void close() throws IOException{} This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException. 2 protected void finalize()throws IOException {} This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. 3 public void write(int w)throws IOException{} This methods writes the specified byte to the output stream. 4 public void write(byte[] w) Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following links:
ByteArrayOutputStream
The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer.
There are following forms of constructors to create ByteArrayOutputStream objects Following constructor creates a buffer of 32 byte:
OutputStream bOut = new ByteArrayOutputStream()
Following constructor creates a buffer of size int a:
OutputStream bOut = new ByteArrayOutputStream(int a)
Once you have ByteArrayOutputStream object in hand then there is a list of helper methods which can be used to write the stream or to do other operations on the stream.
1 public void reset()
This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded.
2 public byte[] toByteArray()
This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array.
3 public String toString()
Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer.s content.
4 public void write(int w)
Writes the specified array to the output stream.
5 public void write(byte []b, int of, int len)
Writes len number of bytes starting from offset off to the stream.
6 public void writeTo(OutputStream outSt)
Writes the entire content of this Stream to the specified stream argument.
Example:
Following is the example to demonstrate ByteArrayOutputStream and ByteArrayOutputStream
import java.io.*;
public class ByteStreamTest
{
public static void main(String args[])throws IOException
{
n ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);
while( bOutput.size()!= 10 )
{
// Gets the inputs from the user
bOutput.write(System.in.read());
}
byte b [] = bOutput.toByteArray();
System.out.println("Print the content");
for(int x= 0 ; x < b.length; x++)
{
//printing the characters System.out.print((char)b[x] + " ");
}
System.out.println(" ");
int c;
ByteArrayOutputStream bInput = new ByteArrayOutputStream(b);
System.out.println("Converting characters to Upper case " );
for(int y = 0 ; y < 1; y++ )
{
while(( c= bInput.read())!= -1)
{
System.out.println(Character.toUpperCase((char)c));
}
bInput.reset();
}
}
}
Here is the sample run of the above program:
asdfghjkly Print the content a s d f g h j k l y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y
DataOutputStream
The DataOutputStream stream let you write the primitives to an output source.
Following is the constructor to create an DataOutputStream.
DataOutputStream out = DataOutputStream(OutputStream out);
Once you have DataOutputStream object in hand then there is a list of helper methods which can be used to write the stream or to do other operations on the stream.
1 public final void write(byte[] w, int off, int len)throws IOException :
Writes len bytes from the specified byte array starting at point off , to the underlying stream.
2 Public final int write(byte [] b)throws IOException :
Writes the current number of bytes written to this data output stream. Returns the total number of bytes write into the buffer.
3 (a) public final void writeBooolean()throws IOException, (b) public final void writeByte()throws IOException,
(c) public final void writeShort()throws IOException (d) public final void writeInt()throws IOException :
These methods will write the specific primitive type data into the output stream as bytes.
4 Public void flush()throws IOException Flushes the data output stream.
5 public final void writeBytes(String s) throws IOException :
Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.
Example:
Following is the example to demonstrate DataInputStream and DataInputStream.
This example reads 5 lines given in a file test.txt and convert those lines into capital letters and finally copies them into another file test1.txt.
import java.io.*;
public class Test
{
public static void main(String args[])throws IOException
{
DataInputStream d = new DataInputStream(new FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt"));
String count; while((count = d.readLine()) != null)
{
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}
Here is the sample run of the above program:
THIS IS TEST 1 ,
THIS IS TEST 2 ,
THIS IS TEST 3 ,
THIS IS TEST 4 ,
THIS IS TEST 5 ,
Example:
Following is the example to demonstrate InputStream and OutputStream:
import java.io.*;
public class fileStreamTest{ public static void main(String args[])
{
try
{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("C:/test.txt");
for(int x=0; x < bWrite.length ; x++)
{
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("C:/test.txt");
int size = is.available();
for(int i=0; i< size; i++)
{
System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e)
{
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers in binary format.
Same would be output on the stdout screen.
File Navigation and I/O:
There are several other classes that we would be going through to get to know the basics of File Navigation and I/O. 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.
There are following constructors to create a File object:
Following syntax creates a new File instance from a parent abstract pathname and a child pathname string.
File(File parent, String child);
Following syntax creates a new File instance by converting the given pathname string into an abstract pathname.
File(String pathname)
Following syntax creates a new File instance from a parent pathname string and a child pathname string.
File(String parent, String child)
Following syntax creates a new File instance by converting the given file:
URI into an abstract pathname.
File(URI uri)
Once you have File object in hand then there is a list of helper methods which can be used manipulate the files.
1 public String getName()
Returns the name of the file or directory denoted by this abstract pathname.
2 public String getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
3 public File getParentFile()
Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not name a parent directory.
4 public String getPath()
Converts this abstract pathname into a pathname string.
5 public boolean isAbsolute()
Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise
6 public String getAbsolutePath()
Returns the absolute pathname string of this abstract pathname.
7 public 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.
8 public 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.
9 public 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
10 public 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.
11 public 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
12 public 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.
13 public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory.
14 public boolean createNewFile() throws IOException
Atomically 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.
15 public 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.
16 public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
17 public String[] list()
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
18 public 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.
20 public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
21 public 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.
22 public boolean mkdir()
Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise
23 public 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.
24 public boolean renameTo(File dest) Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise
25 public 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 .
26 public 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.
27 public static File createTempFile(String prefix, String suffix, File directory) throws IOException
Creates 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.
28 public static File createTempFile(String prefix, String suffix) throws IOException
Creates 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.
29 public 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.
30 public int compareTo(Object o)
Compares this abstract pathname to another object. Returns 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.
31 public 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.
32 public String toString()
Returns the pathname string of this abstract pathname. This is just the string returned by the getPath() method.
Example:
Following is the example to demonstrate File object:
import java.io.File;
public class DirList
{
public static void main(String args[])
{
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}
This would produce following result:
Directory of /mysql
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory
FileReader Class This class inherits from the InputStreamReader class.
FileReader is used for reading streams of characters.
This class has several constructors to create required objects.
Following syntax creates a new FileReader, given the File to read from.
FileReader(File file)
Following syntax creates a new FileReader, given the FileDescriptor to read from.
FileReader(FileDescriptor fd)
Following syntax creates a new FileReader, given the name of the file to read from.
FileReader(String fileName)
Once you have FileReader object in hand then there is a list of helper methods which can be used manipulate the files.
SN Methods with Description
1 public int read() throws IOException
Reads a single character. Returns an int, which represents the character read.
2 public int read(char [] c, int offset, int len)
Reads characters into an array. Returns the number of characters read.
Example:
Following is the example to demonstrate class:
import java.io.*;
public class FileRead{ public static void main(String args[])throws IOException
{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file); // Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a);
// reads the content to the array
for(char c : a)
System.out.print(c);
//prints the characters one by one
fr.close();
}
}
This would produce following result:
This is an example FileWriter Class This class inherits from the OutputStreamWriter class.
The class is used for writing streams of characters.
This class has several constructors to create required objects. Following syntax creates a FileWriter object given a File object.
FileWriter(File file)
Following syntax creates a FileWriter object given a File object.
FileWriter(File file, boolean append)
Following syntax creates a FileWriter object associated with a file descriptor.
FileWriter(FileDescriptor fd)
Following syntax creates a FileWriter object given a file name.
FileWriter(String fileName)
Following syntax creates a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
FileWriter(String fileName, boolean append)
Once you have FileWriter object in hand then there is a list of helper methods which can be used manipulate the files.
1 public void write(int c) throws IOException: Writes a single character.
2 public void write(char [] c, int offset, int len)
Writes a portion of an array of characters starting from offset and with a length of len.
3 public void write(String s, int offset, int len)
Write a portion of a String starting from offset and with a length of len.
Example:
Following is the example to demonstrate class:
import java.io.*;
public class FileRead
{
public static void main(String args[])throws IOException
{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a);
// reads the content to the array
for(char c : a)
System.out.print(c);
//prints the characters one by one
fr.close();
}
}
This would produce following result:
This is an example
Directories in Java:
Creating Directories:
There are two useful File utility methods which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.File;
public class CreateDir
{
public static void main(String args[])
{
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
Compile and execute above code to create "/tmp/user/java/bin".
Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.
Reading Directories:
A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory, the isDirectory( ) method will return true. You can call list( ) on that object to extract the list of other files and directories inside.
The program shown here illustrates how to use list( ) to examine the contents of a directory:
import java.io.File;
public class DirList
{
public static void main(String args[])
{
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}
This would produce following result:
Directory of /mysql
bin is a directory
lib is a directory
demo is a directory t
est.txt is a file
README is a file
index.html is a file
include is a directory
0 comments:
Post a Comment