Sunday, June 13, 2021

Java - How to Convert Java Array to Iterable?

1. Overview

In this tutorial, We will learn how to convert java array to iterable in different ways with example programs.

First we will go thorough the basic one how to iterate over the array values. Next, how to convert the array to Iterable using legacy java api and finally using java 8 api for java array iterator.

Bonus section on how to convert string to iterable with a delimiter.

Java - How to Convert Array to Iterable?



2. Create a iterator over the array using loops


Running a for loop over a array to create iterable logic to get the each value from array based on the index.
package com.javaprogramto.arrays.toiterabale;

/**
 * 
 * Array Iterate example using loops
 * 
 * @author javaprogramto.com
 *
 */
public class ArrayIterate {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};
		
		// iterating array over its values.
		for(int index=0; index< names.length ; index++) {
			System.out.println(names[index]);
		}
	}
}

 
Output:
john
Amal
Paul
 

3. Convert Java Array to Iterable using legacy java before JDK 8


First we will convert the array to list using Arrays.asList() method. Next, convert list to Iterable in java using list.iterator() method.

Finally, iterate the iterator over the while loop to get the all the values.

Array to Iterable Example:
package com.javaprogramto.arrays.toiterabale;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * Example to convert Java Array to Iterable before Java 8
 * 
 * @author javaprogramto.com
 *
 */
public class JavaArrayToIterableExample {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};
		
		// string array to list conversion
		List<String> namesList = Arrays.asList(names);
		
		// List to iterable
		Iterator<String> it = namesList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
	}
}
 
Output:
john
Amal
Paul
 

4. Convert Java Array to Iterable Using Java 8 Stream


In the above section, we called Arrays.asList() method to convert the array to List. But, now will use another method from java 8 stream api Arrays.stream(array) method which takes input array and returns a Stream of array type.

Arrays.stream() method provides the arrays to access the stream api and use the power of parallel execution on larger arrays.

But for now, after getting the Stream<String> object then you need to call the iterator() method on stream to convert Stream to iterable.

Do not worry, if you are new to the java 8, the below program is break down into multiple steps. And also provided a single line solution.
import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.Stream;

/**
 * 
 * Example to convert Java Array to Iterable using Java 8 Arrays.stream()
 * 
 * @author javaprogramto.com
 *
 */
public class JavaArrayToIterableExampleJava8 {

	public static void main(String[] args) {

		// string array
		String[] names = new String[] {"john", "Amal", "Paul"};

		System.out.println("Multi line solution");
		// Convert string array to Stream<String>
		Stream<String> namesList = Arrays.stream(names);
		
		// Stream to iterable
		Iterator<String> it = namesList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		// singel line
		System.out.println("\nIn single line");
		Arrays.stream(names).iterator().forEachRemaining(name -> System.out.println(name));
	}
}
 

Multiline and single line solutions provide the same output. If you are going to use in the realtime project then use it as single line statement as you want to fell like expert and take the advantage of stream power.
Multi line solution
john
Amal
Paul

In single line
john
Amal
Paul

 

5. Bonus - Convert String to Iterable


Applying iterable on string is quite simple if you have understood the above code correctly. What we need is now to convert the String to String array with space or if the string has any delimiter.

After getting the string array then apply the same logic as java 8 streams as below.
public class JavaStringToIterableExampleJava9 {

	public static void main(String[] args) {

		// string 
		String numbers = "1 2 3 4 5 6";

		// string to string array
		String[] numbersArray = numbers.split(" ");

		System.out.println("Multi line solution");
		// Convert string array to Stream<String>
		Stream<String> numbersList = Arrays.stream(numbersArray);
		
		// Stream to iterable
		Iterator<String> it = numbersList.iterator();
		
		// printing each value from iterator.
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		
		// singel line
		System.out.println("\nIn single line");
		Arrays.stream(numbersArray).iterator().forEachRemaining(name -> System.out.println(name));
	}
}
 
Output:
Multi line solution
1
2
3
4
5
6

In single line
1
2
3
4
5
6

 

6. Conclusion


In this article, you've seen how to convert the Array to iterable and get the each value from iterator using legacy and new java 8 api.

And also how to convert String to Iterable in java?



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.