Posts

Showing posts with the label Java IO

How to obtain a list of files in a folder

In this blog post, I will be explaining how you can obtain a list of files in a folder. Consider the following code snippet: package learnjava.io;import java.io.File;public class FilesInFolderDemo {public static void main(String[] args) {String folderName = "F:/TestFolder";File file = new File(folderName);if (file.exists() && file.isDirectory()) { // check if file exists & is a folderFile[] files = file.listFiles(); //get list of filesif (files.length > 0) {System.out.println("There are " + files.length + " files in the folder");for(int i = 0; i < files.length;i++){System.out.println("File name is "+files[i]);}} else { //empty folder!System.out.println("Folder is empty !");}} else {System.out.println("Folder "+folderName+" is missing or is not a folder");}}}   There is a method called File.list on the file interface. If the File object corresponding to the specified path is a directory, then th...

How to read a CSV file via Java

Image
In this blog post, I will be covering how you can read a CSV file via Java. What is a CSV file? CSV stands for Comma Separated Values.  The fields in a CSV file are separated by commas.  So for example, a CSV file will be seen in Notepad as follows:   However, if you open the same CSV file in Excel and will be seen as follows:   A CSV file is used to store tabular data. You can open a CSV file in Microsoft Excel. Code to read CSV file Consider the following code sample: package learnjava.io;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class ReadCSVDemo {public static void main(String[] args) {String fileName="F:/Test.csv";try {BufferedReader br = new BufferedReader(new FileReader(fileName));String str = br.readLine();while(str != null){String[] contents = str.split(",");for(String cell:contents){System.out.print(cell);}str = br.readLine();System.out.println...

How to find the free space in a drive via Java

In this blog post, I will be explaining how you can find the free space in a drive via Java. Consider the following code: package learnjava.io;import java.io.File;public class FindFreeSpaceDemo {public static void main(String[] args) {String fileName = "C:/";File file = new File(fileName);long freeSpace = file.getFreeSpace();System.out.println("freeSpace = "+freeSpace/1000000000+ " GB");}}   There is a method File.getFreeSpace . This returns the number of bytes available on the drive that is encapsulated by the current File object. According to the API documentation, the number of bytes is a hint and not a guarantee. There is another method called File.getUsuableSpace .  This returns the number of bytes available to the virtual machine. This method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than the  File.getFreeSpace  meth...

How to find the total space in a drive in Java

In this blog post, I will be explaining how you can find the total space available in a drive via Java. Consider the following code snippet:   package learnjava.io;import java.io.File;public class FindTotalSpaceDemo {public static void main(String[] args) {String fileName = "C:/";File file = new File(fileName);long totalSpace = file.getTotalSpace();System.out.println("totalSpace = "+totalSpace/1000000000+ " GB");}}   There is a method called File.getTotalspace . This returns the number of bytes available on the partition that is encapsulated by the file object.

How to make a file read-only in Java

Image
In this blog post, I will be explaining how you can make a file read-only in Java. Consider the following code snippet: package learnjava.io;import java.io.File;public class ReadOnlyDemo {public static void main(String[] args) {String fileName = "F:/Test1.txt";File file = new File(fileName);if(file.setReadOnly()){System.out.println("File is now readonly");}elseSystem.out.println("Failed to make the file readonly");}} There is a method called File.setReadOnly . This makes a file as read only. It returns true if the file is made readonly successfully. If the file does not exist at that path, or if any other issue occurs, it returns false. So if you run the above code snippet, the file “F:/Test1.txt” will be made as readonly. If you try to edit and save it, you will see the following error:

How to create a Directory in Java

In this blog post, I will be covering how you can create a directory in Java. Consider the following code snippet: package learnjava.io;import java.io.File;public class CreateDirectory {public static void main(String[] args) {String fileName = "C:/Parent/Demo";File file = new File(fileName);boolean created = file.mkdirs();if(created)System.out.println("Directory created successfully");elseSystem.out.println("Failed to created directories");}}   There is a File.mkdirs method. This creates the directory corresponding to the File object including any non-existent parent directories. It returns a true if the directory was created successfully, otherwise it returns a false. In this case, it will print the following output (Assuming there is no error in creating the directory): Directory created successfully There is also a File.mkdir method. This creates a directory corresponding to the path specified, but does not create parent directories. So if the par...

How to create a new file using Java

In this blog post, I will be demonstrating how you can create a new empty file via Java. Consider the following code snippet: package learnjava.io;import java.io.File;import java.io.IOException;public class CreateFileDemo {public static void main(String[] args) {String fileName = "C:/Test2.txt";File file = new File(fileName);try {if (file.createNewFile())System.out.println("File created successfully");elseSystem.out.println("There was an error in creating the file");} catch (IOException e) {System.out.println("There was an exception in creating the file:"+e.getMessage());}}} There is a method called File.createNewFile . This creates a new file corresponding to the path in the File object. It returns a boolean value if the file is created successfully. If there is already a file at the path with the same name or if there is any other issue in creating the file, then this method returns a false. Note that the  File.createNewFile can throw an IOExc...

How to rename a file

In this blog post ,I will be showing you how you can rename a file. Consider the following code snippet: package learnjava.io;import java.io.File;public class RenameFileDemo {public static void main(String args[]){String fileName = "C:/Test.txt";String newFileName = "C:/test2.txt";File file = new File(fileName);if(file.exists()){File newFile = new File(newFileName);boolean renamed = file.renameTo(newFile);if(renamed)System.out.println("File renamed successfully");elseSystem.out.println("There was an error in renaming the file");}elseSystem.out.println("File is missing");}} If you run this code, it will produce the following output: File renamed successfully   There is a method called File.renameTo which can be used to rename a file. It accepts as argument a file object. The file object should be constructed with the new name to be given to the file. Note that the full path needs to be specified.

How to delete a folder in Java

In this blog post, I will be demonstrating how you can delete a folder in Java. Consider the following code snippet: </pre>package learnjava.io;import java.io.File;public class DeleteDirectory {public static void main(String[] args) {String fileName = "F:/TestFolder";File file = new File(fileName);if (file.exists()) {if (file.isDirectory()) {File[] files = file.listFiles();if (files.length == 0) {System.out.println("Folder is empty so deleting it");if (file.delete()) {System.out.println("Deleted file successfully");} elseSystem.out.println("Error in deleting file");} else {System.out.println("There are " + files.length + " files in the folder, so folder cannot be deleted");}} else {System.out.println("F:/Test.txt is not a folder");}} elseSystem.out.println("Folder F:/TestFolder1 is missing, so could not be deleted");}}<pre> There is a file.delete method that can be used to delete a folder. Howe...

How to Delete a file

In this blog post, I will be demonstrating how you can delete a file in Java. Consider the following code snippet: package learnjava.io;import java.io.File;public class DeleteFile {public static void main(String[] args) {String fileName = "D:/Test.txt";File file = new File(fileName);if (file.exists()) {if (file.delete()) {System.out.println("Deleted file successfully");} elseSystem.out.println("Error in deleting file");} elseSystem.out.println("File is missing, so could not be deleted");}}   There is a File.delete method available to delete a file. It returns true, if the delete was successful, otherwise returns a false. So if you run the above code snippet, the following output will be printed (Assuming there is a file called test.txt on D Drive):   Deleted file successfully

How to check if a file exists at the specified path

In this blog post, I will be explaining how you can check if a file exists at a specified path. Consider the following code snippet: public class FileExists {public static void main(String args[]){String fileName = "C:/Test.txt";File file = new File(fileName);if(file.exists()){System.out.println("File is present");}elseSystem.out.println("File is missing");}}   Here the File.exists method is used. This returns a true if a file with the specified name exists at the path specified, otherwise it returns a false. If you run this code, you will get the following output (Assuming there is a file on C drive called test.txt): File is present

How to read input from the user in Java

This blog post demonstrates how to read a user’s input in Java.  You can use the following code snippet: public class ReadInput {public static void main(String args[]){Scanner scanner = new Scanner(System.in);System.out.println("Enter your input:");int num = scanner.nextInt();System.out.println("The number entered is "+num);}}   This code uses the Scanner class. This class has a method called nextInt which is used to read an integer input. In addition to this method, it has several other methods like nextDouble , nextFloat  ,etc which can be used to read other data types.  In addition, it also has a method called next , which can be used to read String data.

How to read a file in Java

In Java, you can use the BufferedReader class as follows in order to read a file:   package demo;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class MyTextFileReader {public static void main(String args[]){try {BufferedReader br = new BufferedReader(new FileReader(new File("F:/test.txt")));String line = null;while ((line = br.readLine()) != null) {System.out.println(line);}} catch ( IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}