Core JAVA
Java Runtime Environment (JRE)
Java Virtual Machine (JVM)
Java overview
Java basics
Java Objects and classes
Java Constructors
Java basic datatypes
Java variable types
Java modifiers/Access Modifiers In Java
Java Basic Operators
Java Loops and Controls
Java conditions
Java numbers and characters
Java strings
Java arrays
Java date time
Java methods
Java file and IO operations
Java exceptions
Inner class
Java OOPs Concepts
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java Interface
Cohesion and Coupling
Association, Aggregation and Composition
Java Collections
Java ArrayList
Java LinkedList
Set and HashSet
LinkedHashSet and TreeSet
Queue and PriorityQueue
Deque and PriorityQueue
Java Map Interface
Java HashMap
Internal Working Of Java HashMap
Java Mutithread
Methods of Thread In Java
Join , run & Start Method in Threads
Difference b/w start & run Methods in Threads
Java Concurrency Package & its Features
CountDownLatch, CyclicBarrier, Semaphore and Mutex in Thread
Java File and IO Operations
Java file and IO have a lot of classes and methods to read and write files and do IO operations. Package named java.io contains these useful classes and methods.
Java File Class
In java class java.io.File is used to create files and also contains useful methods to check file or file system.
Java File Creation
Simple code to create file object for file named “testfile.txt”
import java.io.File; public class FilesExample { public static void main(String[] args) { File sampleFile = new File("testfile.txt"); } }
Methods in Java File Class
Below are very useful methods of file class.
- canRead() – Checks if file is readable or not and return boolean.
- canWrite() – Checks if file can be written or not and returns boolean.
- createNewFile() – Creates an empty file.
- exists() – Checks if file or directory exists or not.
- getName() – Returns name of file.
- length() – Returns size of file in bytes.
- getAbsolutePath() – Returns abs path of file.
- list() – Returns list of files in a file system or directory.
- mkdir() – Creates a directory.
- mkdirs() – Creates directory and parents of directoty as well.
- isDirectory() – Checks if file is a directory or not.
- delete() – Deletes the file.
- deleteOnExit() – This method request deletetion of file when java or JVM terminates, should be used carefully.
- getPath() – Returns path.
Java File Creation and Writing
In below example we will use File class to create a file and FileWriter to write a file.
File read write operation may raise exception related to file IO, so IOException class is used as well. See below program’s imports.
Example:
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FilesExample { public static void main(String[] args) throws IOException { File sampleFile = new File("testfile.txt"); //Creates file FileWriter fileWriter = new FileWriter("testfile.txt"); //Creates writer to write on above created file fileWriter.write("Hello I am file, created by java file writer"); fileWriter.close(); } }
Output:
A file will be created in current directory with name “testfile.txt” and content of file will be “Hello I am file, created by java file writer”
Java Read Files Using Scanner
In above examples we saw how to create and write a file, now let’s see how we can read a file.
We will use Scanner class to read a file.
Example:
import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class FilesExample { public static void main(String[] args) throws IOException { File sampleFile = new File("testfile.txt"); //Creates file FileWriter fileWriter = new FileWriter("testfile.txt"); //Creates writer to write on above created file fileWriter.write("Hello I am file, created by java file writer"); // write something to file fileWriter.close(); //Scanner to read file Scanner scanner = new Scanner(sampleFile); while ((scanner.hasNext())){ System.out.println(scanner.nextLine()); } } }
Output:
Hello I am file, created by java file writer
Directories in Java
Directories are nothing but folder in a computer in simple words. In java File class there are mkdir() and mkdirs() are useful methods to create directory.
Example Creating Directories:
import java.io.File; public class FilesExample { public static void main(String[] args) { String dirName = "test"; File dir = new File(dirName); dir.mkdir(); //this will create dir test String dirName2 = "/abc/test"; File dir2 = new File(dirName2); dir.mkdirs(); //this will create dir with parent dir as well } }
Listing Directories and Files
File class has a list() method which lists all files and directories in a directory.
Example:
import java.io.File; public class FilesExample { public static void main(String[] args) { String dirName = "test"; //this dir already exists with some file and sub dir File dir = new File(dirName); String[] dirArray = dir.list(); //print all files and paths for(String name : dirArray){ System.out.println(name); } } }
Output:
dummy.txt
dummy
Java FileInputStream
FileInputStream is a java class used to read a file.
Example:
Below we have a file samplefile.txt and with help of FileInputStream we created an object to read stream of file.
File file = new File("samplefile.txt"); InputStream inputStream = new FileInputStream(file);
Methods in FileInputStream:
- public int read(int r)throws IOException{} – This is used to read specific byte of data from input stream.
- public int read(byte[] r) throws IOException{} – Another method to read data from stream.
- public void close() throws IOException{} – This method closes the stream and releases file and its access which may be needed by underlying OS.
- public int available() throws IOException{} – Returns number of bytes available from input stream.
Java FileOutputStream
FileOutputStream is a class which is used to write file.
Example:
File file = new File("samplefile.txt"); OutputStream outputStream = new FileOutputStream(file);
Methods in FileOutputStream
- public void write(int w)throws IOException{} – Writes data.
- public void write(byte[] w) – Writes byte data.
- public void close() throws IOException{} – Closes stream.
Example FileInputStream and FileOutputSteam
Below is a sample code which reads from one input file using FileInputStream and writes to another using FileOutputSteam.
import java.io.IOException; public class FilesExample { public static void main(String[] args) throws IOException { FileInputStream fileInputStream = new FileInputStream("testfile.txt"); //reader input stream FileOutputStream fileOutputStream = new FileOutputStream("testoutput.txt"); //writer inpur stream int data; while((data = fileInputStream.read()) != -1) { fileOutputStream.write(data); } } }
Java File Delete
We can use file class delete() method to delete files and folders.
Example showing how to delete file and folder:
import java.io.File; public class FilesExample { public static void main(String[] args) { //Below code will delete file String fileName = "testfile.txt"; //dummy file File file = new File(fileName); file.delete(); //Below code will delete folder test String dirName = "test"; //this dir already exists with some file and sub dir File dir = new File(dirName); dir.delete(); } }
Output:
Above code will delete file named “testfile.txt” and then delete folder (directory) named “test”.
References
Below are some of references from oracle official page on File and IO:
Next Article To Read
If you missed our previous article worth reading: Java Methods
Now, you may explore our next articles: