Java Tutorials for Freshers and Experience developers, Programming interview Questions, Data Structure and Algorithms interview Programs, Kotlin programs, String Programs, Java 8 Stream API, Spring Boot and Troubleshooting common issues.
Wednesday, December 1, 2021
How to use PrintWriter and File classes in Java?
Java Printwriter New Line
1. Overview
Tuesday, November 30, 2021
Java PrintWriter
1. Overview
public class PrintWriter extends Writer
Monday, June 7, 2021
Java Convert File Contents to String
1. Overview
Friday, June 4, 2021
Java - How to Delete Files and Folders?
1. Overview
In this tutorial, We will learn how to delete the files and folders in java.
Let us learn the example programs on file deletion and folder removal in java.
2. Java Files Delete Example
First, Use delete() method on the file object to delete the file. Returns true if the file is delete successfully and else return false if there are any failures.
In the below program, we have taken two files test.log file is present in the location and no-file.log does not exists on the location.
Let us see the behaviour of delete() method.
package com.javaprogramto.files.delete; import java.io.File; /** * How to delete the file in java using File api delete() method. * * @author JavaProgramTo.com * */ public class FileDelete { public static void main(String[] args) { // File deletion success String fileName = "src/main/java/com/javaprogramto/files/delete/test.log"; File file = new File(fileName); boolean isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("File deleted without any errors for "+fileName); } else { System.out.println("File deletion is failed"); } // File deletion error. fileName = "src/main/java/com/javaprogramto/files/delete/no-file.log"; file = new File(fileName); isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("File deleted without any errors for "+fileName); } else { System.out.println("File deletion is failed for "+fileName); } } }
Output:
File deleted without any errors for src/main/java/com/javaprogramto/files/delete/test.log File deletion is failed for src/main/java/com/javaprogramto/files/delete/no-file.log
3. Java Delete Folder Example
Next, we will try to delete the folder which is having the files and next empty folder deletion using delete() method.
package com.javaprogramto.files.delete; import java.io.File; /** * How to delete the folder in java using File API delete() method. * * @author JavaProgramTo.com * */ public class FileDeleteFolder { public static void main(String[] args) { // Folder deletion not done String folderName = "src/main/java/com/javaprogramto/files/delete"; File file = new File(folderName); boolean isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("Folder with files is deleted"); } else { System.out.println("Folder with files is not deleted"); } // Empty Folder deletion success . folderName = "src/main/java/com/javaprogramto/files/emptyfolder"; file = new File(folderName); isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("Empty Folder deleted "); } else { System.out.println("Empty Folder deletion is failed for "+folderName); } } }
Output:
Folder with files is not deleted Empty Folder deleted
Note: if the folder is empty then only folder will be deleted and folder which has files won't be deleted. But, we can delete the files folder after deleting all files.
4. Conclusion
In this article, we've seen how to delete the files and folder in java with examples.
Thursday, April 1, 2021
How To Make A File Read Only Or Writable In Java?
1. Overview
2. Java Example To Set File As Read Only
package com.javaprogramto.files.readonlywrite; import java.io.File; /** * Example to set the file as read-only format. * * @author javaprogramto.com * */ public class FileReadOnlyExample { public static void main(String[] args) { File newFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-read-only.txt"); // setting the file as read only boolean isSetToReadOnly = newFile.setReadOnly(); System.out.println("isSetToReadOnly value : "+isSetToReadOnly); if(isSetToReadOnly) { System.out.println("make-read-only.txt is set to read-only form"); }else { System.out.println("Failed to set file as read only for make-read-only.txt"); } } }
isSetToReadOnly value : true make-read-only.txt is set to read-only form
3. Java Example To Check File Can Be Writable
package com.javaprogramto.files.readonlywrite; import java.io.File; /** * Example to check the file is writable or not. * * @author javaprogramto.com * */ public class FileCanWriteExample { public static void main(String[] args) { File newFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-read-only.txt"); // checking the is allowed for modifications. boolean isSetToReadOnly = newFile.canWrite(); System.out.println("Can write the file ? : " + isSetToReadOnly); File breandNewFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-new-file.txt"); // checking the is allowed for modifications. isSetToReadOnly = breandNewFile.canWrite(); System.out.println("Can write the breandNewFile file ? : " + isSetToReadOnly); } }
Can write the file ? : false Can write the breandNewFile file ? : true
4. Java Example To Make Writable from Read Only Form
package com.javaprogramto.files.readonlywrite; import java.io.File; /** * Example to convert the file from read only to writable form. * * @author javaprogramto.com * */ public class FileSetWritableExample { public static void main(String[] args) { File newFile = new File("src/main/java/com/javaprogramto/files/readonlywrite/make-read-only.txt"); // Changing the file from read only to writable format. boolean isWritableNow = newFile.setWritable(true); System.out.println("Can write the file ? : " + isWritableNow); } }
Can write the file ? : true
5. Conclusion
Tuesday, March 30, 2021
Java 8 - How To Read A File?
1. Overview
In this tutorial, We'll learn how to read a file line by line in java and print the files content onto console with example program.
First, let us use the older java version for example demonstration and next will learn how to do the same in the newer java 8 api.
Saturday, November 14, 2020
How To Get The Current Working Directory In Java?
1. Overview
2. Example 1 - Get Current Working Directory With System.getProperty user.dir
public class CurrentDirectorySystemGetpropertyExample { public static void main(String[] args) { // Calling the getPropery() method with argument "user.dir" String currentDirectoryLocation = System.getProperty("user.dir"); System.out.println("Current working directoruy : " + currentDirectoryLocation); } }
Current working directoruy : /Users/javaprogramto/Documents/workspace/CoreJava
3. Example 2 - Get Current Working Directory With Paths Class
import java.nio.file.Path; import java.nio.file.Paths; public class CurrentDirectoryPathGetExample { public static void main(String[] args) { // Current location from path. Path currentPath = Paths.get(""); // getting the location from Path.toAbsolutePath() String currentLocation = currentPath.toAbsolutePath().toString(); System.out.println("Current working directoruy : " + currentLocation); } }
4. Example 3 - Get Current Directory With FileSystem.getDetaults()
import java.nio.file.FileSystems; import java.nio.file.Path; public class CurrentDirectoryFileSystemsExample { public static void main(String[] args) { // Current location from FileSystems. Path currentPath = FileSystems.getDefault().getPath("."); // getting the location from Path.toAbsolutePath() String currentLocation = currentPath.toAbsolutePath().normalize().toString(); System.out.println("Current working directoruy : " + currentLocation); } }
5. Conclusion
String currentDir = new File("").getAbsolutePath();
Wednesday, July 1, 2020
Java 8 Stream – How to Read a file line by line
1. Introduction
In this article, You'll learn how to read a file line by line using Java 8 Streams new API methods from Files, BufferedReader lines() methods.
We have already discussed how to read the large files efficiently in java with Streams.
Friday, April 3, 2020
Java Examples to Create New Empty File and A Temporary File
1. Overview
In this tutorial, We'll be learning how to create a file in java and how to create a temp file in java.
Example programs demonstrated in the following methods.
createNewFile() createTempFile()
createNewFile(): method is used to create a new empty file.
createTempFile(): method is used to create a temporary file.
Tuesday, February 25, 2020
Java 8 Files walk() Examples
1. Overview
In this tutorial, We'll be learning the Files API walk() method in java 8. walk() method is part of the Files class and java.nio.file package.
This method is used to walk through any given directory and retrieves Stream<Path> as the return value. This method traverses through all its subdirectories as well.
API Description:
Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.
Note: This method must be used within a try-with-resources statement.
In this article, We'll see its syntax and example programs on how to list all the files in the directory, list directories and specific file patterns such as .csv or file name contains 'Match' word.
Thursday, February 13, 2020
Files Compressing and Decompressing in Java (Zipping and Unzipping)
1. Introduction
In this tutorial, We will be learning how to compress a file in java and how to decompress the same compressed file using java java.util.zip package.
Java is built with zipping(archiving) files utilities in java.util.zip which you can find all the zipping and unzipping related utilities.
In this article, we will see how to compress a file, multiple files, and files in folder or directory. At last, we will how to unzip an archived file. All the examples shown are can be done in java 8 or higher versions.
Friday, January 10, 2020
Sunday, January 5, 2020
Java Program: Read File Line By Line
1. Overview
In this programming tutorial, We'll learn today how to read a text file line by line. Java programs are shown for all possible ways to read file contents.
One of the file tutorials, we have already discussed in-depth on How to read large text files efficiently in java.
We will learn different approaches to read file line by line as String and pass this string to a separate method to process it.
Following are the java API class that provides a way to process the files.
BufferedReader
Scanner
Files
RandomAccessFile
Saturday, December 28, 2019
Java List or Traverse All Files in Folder Recursively (Java 8 Files.walk() Example)
1. Overview
In this programming tutorial, we are showing an example program on how to list or traverse all files and folders including subfolders in a directory using the following methods.
A) Using the classic approach
B) Using Java 8 methods
Java 12 Files mismatch Method Example to Compare two Files
Tuesday, April 30, 2019
Java 12 Files mismatch Method Example to Compare two Files
1. Java 12 Files mismatch Overview
In this post, We will learn about new method mismatch() added in Java 12 to Files class. Files class is in package java.nio.file.Files.java.nio.file.Files class consists exclusively of static methods that operate on files, directories, or other types of files. In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.
We will learn how to compare two files using Files.mismatch method.
JDK 12 introduces the new way to determine equality between two files.
Thursday, March 28, 2019
Program: How to write or store data into temporary file in java?
Below is the example program.
Writing data into Temp File:
package examples.java.w3schools.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class CreatingTempFileExample { public static void main(String[] args) { // Example program using BufferedWriter. File tempFile = null; BufferedWriter writer = null; try { // Creating ta temporary file in Temp directory. tempFile = File.createTempFile("MyTempFile", ".tmp"); writer = new BufferedWriter(new FileWriter(tempFile)); writer.write("Writing data into temp file!!!. This is a temp file."); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) writer.close(); } catch (Exception ex) { } } System.out.println("Stored data in temporary file."); System.out.println("Temp file location: " + tempFile.getAbsolutePath()); } }
Output:
Stored data in temporary file. Temp file location: C:\Users\user\AppData\Local\Temp\1\MyTempFile3113093780191713532.tmp
Popular Posts
- 3 Ways to Fix Git Clone "Filename too long" Error in Windows [Fixed]
- Java Program To Reverse A String Without Using String Inbuilt Function reverse()
- Java Thread.join() Examples to Wait for Another Thread
- Java IS-A and HAS-A Relationship With Examples
- How to create a thread without implementing the Runnable interface in Java?