Showing posts with label Files. Show all posts
Showing posts with label Files. Show all posts

Wednesday, December 1, 2021

How to use PrintWriter and File classes in Java?

1. Overview

In this tutorial, We'll learn how to use PrintWriter class along with the File api classes in java.

In the previous article, we've shown what are the methods of PrintWriter and their examples.

If you want to write some contents to the file using printwriter then you need to make sure the file path given must exist else will get a file not found exception at the runtime.

In this post, we will show you how to always the directory and file is available to the printwriter and avoid errors.

Let us write a few examples to understand the file handling with PrintWriter.


How to use PrintWriter and File classes in Java?

Java Printwriter New Line

1. Overview

In this tutorial, we'll learn how to add the new file to the printwriter in java.

When you use the write() method of print writer then you do not see the new lines for each time you call write() method.

To fix this problem and print the new line \n for each time write the data into the printwriter, you need to use the println() method rather than using any other methods such as write() or print() methods.

If you are new to java, please read the java printwrite methods and exampls.

By end of this post, you will understand write() vs println() of printwriter.

Java Printwriter New Line

Tuesday, November 30, 2021

Java PrintWriter

1. Overview

In this tutorial, We'll learn how to use PrintWriter class in java with examples.

PrintWriter class is present in a package of java.io and PrintWriter class is an implementation of Writer class.
public class PrintWriter
extends Writer

PrintWriter class is used to store or print the formatted representation of the object to the next output stream.


This class implements all methods from PirntStream class.

None of the methods from PrintWriter class does not throw IOException. But some of the contractors may throw IO Exceptions.

To know the errors are present or not, we need to use the checkError() method.

It is not possible to use PrintWriter with Java 8 Streams.

Java PrintWriter

Monday, June 7, 2021

Java Convert File Contents to String

1. Overview

In this tutorial, you'll learn how to convert File contents to String in java.

If you are new to java 8, please read the how to read the file in java 8? we have already shown the different ways to read the file line by line.

Java new Files api has two useful methods to read the file.

readAllLines()
readAllBytes()

Let us write the examples on each method to convert file to string in java.

Java Convert File Contents to String


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.

Java - How to Delete Files and Folders?


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.

GitHub

How to compress and decompress the files in java?

File.delete() API

Thursday, April 1, 2021

How To Make A File Read Only Or Writable In Java?

1. Overview

In this article, We'll learn how to make a file as read only in java. After creating the file in java, we have to specify the file property readOnly flag to true. But, we can not set this flag to true directly.

File api has a utility method setReadOnly() method which returns a boolean value. True is returned if the file is successfully changed to read only form else false is returned.

In the last section of this article, we will learn how to make the writable from read only format.

Example to convert file from writable to read only and vice-versa.

How To Make A File Read Only and Writable In Java?


2. Java Example To Set File As Read Only


Now let us create a class which creates a new File with name make-read-only.txt file. After that just call the method setReadOnly() method. That's all now this file is set to only read only operations.

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");
		}
		
	}
}
 
Output:
isSetToReadOnly value : true
make-read-only.txt is set to read-only form
 

3. Java Example To Check File Can Be Writable


In the above section, we have made the file as read only, but let us check now wether the file is allowed for the modifications or not.

Java File API has another method canWrite() which returns true if the file writable else false that means file is read only.

Look at the below example program. We are just passing the same file name to the File class and directly checking with canWrite() method.

After that created a new file and checked the canWrite() on the new file object.

Observe the outputs for better understanding.
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);
	}
}
 
Output:
Can write the file ? : false
Can write the breandNewFile file ? : true
 

4. Java Example To Make Writable from Read Only Form


Next, let us use the same read-only file and try to change its property to writable using setWritable(boolean).

If true is passed then file becomes writable 
If false is passed then file becomes only readable

Example program is shown below.

This method is very useful when you are working with the unix platform and we can change the files permissions easily from programming.
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);
	}
}
 
Output:
Can write the file ? : true
 

5. Conclusion


In this article, we've seen how to change file permissions from read only to writable and writable to read only in java with examples.



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.

Java 8 - How To Read A File?

Saturday, November 14, 2020

How To Get The Current Working Directory In Java?

1. Overview

In this tutorial, You'll learn how to find the current working directory in java. Finding current directory can be found in various ways with File API.

We should have the basic understanding on the following areas.



In the following sections, all example programs using System, Paths, FileSystems classes.

How To Get The Current Working Directory In Java?



2. Example 1 - Get Current Working Directory With System.getProperty user.dir


Let us look at the first approach.
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);

	}

}
Output:
Current working directoruy : /Users/javaprogramto/Documents/workspace/CoreJava
Java has a System class that provides the way to access the system properties using getProperty() method.

When you call getProperty() method, it expects a right property "user.dir" to get the current directory.

This is a simple way to get where you are in the file system.

3. Example 2 - Get Current Working Directory With Paths Class


Next approach is to get the directory using Paths.get() method.
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);

	}

}

The above program also produces the same result as example 1.

First, use the Paths.get("") method to get the Path object and call toAbsolutePath() which returns the File object.

On top of the file object, just call the toString() method that gives the string representation of current path.

4. Example 3 - Get Current Directory With FileSystem.getDetaults()


Final approach is to get the Path object from FileSystem.getDefaults() method.
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);

	}

}
The above program produces the same output. You can choose needed approach to you.

5. Conclusion


In this article, you've seen the 3 different ways to get the current working directory or location using System, Paths, FileSystems classes.

Another simpler way using File class.
String currentDir = new File("").getAbsolutePath();

GitHub Examples








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.

Java 8 Stream – How to Read a file line by line

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()

Example Programs on Files

createNewFile(): method is used to create a new empty file.
createTempFile(): method is used to create a temporary file.

Java Examples to Create New Empty File and 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.


Java 8 Files walk() Examples



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.

Files Compressing and Decompressing in Java (Zipping and Unzipping)


Friday, January 10, 2020

How to convert InputStream to File in Java

1. Overview


In this tutorial, We'll learn how to convert or write an InputStream to a File.

This can be done in different ways as below.

A) Using plain Java
B) Using java 7 NIO package
C) Apache Commons IO library
D) Guava

How to convert InputStream to File in Java



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.

Java Read File Line By Line


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

Traverse All Files in Folder Recursively


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.

Java 12 API Files mismatch


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?

We will learn how to write the data into a temporary file in java using File class.
Below is the example program.


How to write or store data into temporary file in java

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:

The above program produces the following output and executed in windows operating system.

Stored data in temporary file.
Temp file location: C:\Users\user\AppData\Local\Temp\1\MyTempFile3113093780191713532.tmp

Temporary file is stored in the users Temp location. You can open the file and see its content.