How to convert String to InputStream in Java

In Java, we can use ByteArrayInputStream to convert a String to an InputStream. String str = "mkyong.com"; InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)); Table of contents 1. ByteArrayInputStream 2. Apache Commons IO – IOUtils 3. Download Source Code 4. References 1. ByteArrayInputStream This example uses ByteArrayInputStream to convert a String to an InputStream and saves it …

Read more

How to get free disk space in Java

In Java old days, it lacks of method to determine the free disk space on a partition. But this is changed since JDK 1.6 released, a few new methods – getTotalSpace(), getUsableSpace() and getFreeSpace(), are bundled with java.io.File to retrieve the partition or disk space detail. Example package com.mkyong; import java.io.File; public class DiskSpaceDetail { …

Read more

How to make a file read only in Java

A Java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only. Since JDK 1.6, a new setWritable() method is provided to make a file to be writable again. Example package com.mkyong; import java.io.File; import java.io.IOException; public class FileReadAttribute { public static void main(String[] args) throws IOException { File file …

Read more

How to check if a file is hidden in Java

A Java program to demonstrate the use of java.io.File isHidden() to check if a file is hidden. package com.mkyong; import java.io.File; import java.io.IOException; public class FileHidden { public static void main(String[] args) throws IOException { File file = new File("c:/hidden-file.txt"); if(file.isHidden()){ System.out.println("This file is hidden"); }else{ System.out.println("This file is not hidden"); } } } Note …

Read more

Java object sorting example (Comparable and Comparator)

In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value. 1. Sort an Array To sort an Array, use the Arrays.sort(). String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; Arrays.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + …

Read more

How to sort an Array in java

Java example to show the use of Arrays.sort() to sort an Array. The code should be self-explanatory. import java.util.Arrays; import java.util.Collections; public class ArraySorting{ public static void main(String args[]){ String[] unsortStringArray = new String[] {"c", "b", "a", "3", "2", "1"}; int[] unsortIntArray = new int[] {7,5,4,6,1,2,3}; System.out.println("Before sort"); System.out.println("— unsortStringArray —"); for(String temp: unsortStringArray){ System.out.println(temp); …

Read more

How to sort an ArrayList in java

By default, the ArrayList’s elements are display according to the sequence it is put inside. Often times, you may need to sort the ArrayList to make it alphabetically order. In this example, it shows the use of Collections.sort(‘List’) to sort an ArrayList. import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortArrayList{ public static void main(String …

Read more

How to sort a Map in Java

Few Java examples to sort a Map by its keys or values. Note If you are using Java 8, refer to this article – How to use Stream APIs to sort a Map 1. Sort by Key 1.1 Uses java.util.TreeMap, it will sort the Map by keys automatically. SortByKeyExample1.java package com.mkyong.test; import java.util.HashMap; import java.util.Map; …

Read more

How to initialize an ArrayList in one line

Here’s a few ways to initialize an java.util.ArrayList, see the following full example: InitArrayList.java package com.mkyong.examples; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class InitArrayList { public static void main(String[] args) { //1. Normal way List<String> list = new ArrayList<String>(); list.add("String A"); list.add("String B"); list.add("String C"); System.out.println("List 1……"); for (String temp : list) { System.out.println(temp); …

Read more

How to copy directory in Java

In Java, we can use the Java 1.7 FileVisitor or Apache Commons IO FileUtils.copyDirectory to copy a directory, which includes its sub-directories and files. This article shows a few of the common ways to copy a directory in Java. FileVisitor (Java 7+) FileUtils.copyDirectory (Apache commons-io) Custom Copy using Java 7 NIO and Java 8 Stream. …

Read more

How to check if directory is empty in Java

Here’s an example to check if a directory is empty. Example package com.mkyong.file; import java.io.File; public class CheckEmptyDirectoryExample { public static void main(String[] args) { File file = new File("C:\\folder"); if(file.isDirectory()){ if(file.list().length>0){ System.out.println("Directory is not empty!"); }else{ System.out.println("Directory is empty!"); } }else{ System.out.println("This is not a directory"); } } }

How to delete directory in Java

If we use the NIO Files.delete to delete a non-empty directory in Java, it throws DirectoryNotEmptyException; for legacy IO File.delete to delete a non-empty directory, it returns a false. The standard solution is to loop the directory recursively, and delete all its children’s contents first (sub-files or sub-directories), and delete the parent later. This example …

Read more

How to create directory in Java

In Java, we can use the NIO Files.createDirectory to create a directory or Files.createDirectories to create a directory including all nonexistent parent directories. try { Path path = Paths.get("/home/mkyong/a/b/c/"); //java.nio.file.Files; Files.createDirectories(path); System.out.println("Directory is created!"); } catch (IOException e) { System.err.println("Failed to create directory!" + e.getMessage()); } 1. Create Directory – Java NIO 1.1 We can …

Read more

How to create a temporary file in Java

In Java, we can use the following two Files.createTempFile() methods to create a temporary file in the default temporary-file directory. Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>… attrs) throws IOException Path createTempFile(String prefix, String suffix, FileAttribute<?>… attrs) throws IOException The default temporary file folder is vary on operating system. Windows – %USER%\AppData\Local\Temp Linux – …

Read more

How to append text to a file in Java

This article shows how to use the following Java APIs to append text to the end of a file. Files.write – Append a single line to a file, Java 7. Files.write – Append multiple lines to a file, Java 7, Java 8. Files.writeString – Java 11. FileWriter FileOutputStream FileUtils – Apache Commons IO. In Java, …

Read more

How to delete a temporary file in Java

In Java, we can use the NIO Files.delete() or Files.deleteIfExists() to delete a temporary file, it works the same like delete a regular text file. // create a temporary file Path path = Files.createTempFile(null, ".log"); // delete Files.delete(path); // or if(Files.deleteIfExists(path)){ // success }else{ // file does not exist } 1. Delete Temporary File – …

Read more

How to delete a file in Java

In Java, we can use the NIO Files.delete(Path) and Files.deleteIfExists(Path) to delete a file. 1. Delete a file with Java NIO 1.1 The Files.delete(Path) deletes a file, returns nothing, or throws an exception if it fails. DeleteFile1.java package com.mkyong.io.file; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class DeleteFile1 { public static void main(String[] args) { …

Read more

How to rename or move a file in Java

In Java, we can use the NIO Files.move(source, target) to rename or move a file. import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; //… Path source = Paths.get("/home/mkyong/newfolder/test1.txt"); Path target = Paths.get("/home/mkyong/newfolder/test2.txt"); try{ Files.move(source, target); } catch (IOException e) { e.printStackTrace(); } 1. Rename a file in the same directory. 1.1 This example renames a …

Read more

How to write to file in Java – BufferedWriter

In Java, we can use BufferedWriter to write content into a file. // jdk 7 try (FileWriter writer = new FileWriter("app.log"); BufferedWriter bw = new BufferedWriter(writer)) { bw.write(content); } catch (IOException e) { System.err.format("IOException: %s%n", e); } Note If possible, uses Files.write instead, one line, simple and nice. List<String> list = Arrays.asList("Line 1", "Line 2"); …

Read more

How to write data to a temporary file in Java

The temporary file is just a regular file created on a predefined directory. In Java, we can use the NIO Files.write() to write data to a temporary file. // create a temporary file Path tempFile = Files.createTempFile(null, null); // Writes a string to the above temporary file Files.write(tempFile, "Hello World\n".getBytes(StandardCharsets.UTF_8)); // Append List<String> content = …

Read more

How to construct a file path in Java

In this tutorial, we will show you three Java examples to construct a file path : File.separator or System.getProperty(“file.separator”) (Recommended) File file = new File(workingDir, filename); (Recommended) Create the file separator manually. (Not recommend, just for fun) 1. File.separator Classic Java example to construct a file path, using File.separator or System.getProperty(“file.separator”). Both will check the …

Read more

How to get the temporary file path in Java

In Java, we can use System.getProperty("java.io.tmpdir") to get the default temporary file location. For Windows, the default temporary folder is %USER%\AppData\Local\Temp For Linux, the default temporary folder is /tmp 1. java.io.tmpdir Run the below Java program on a Ubuntu Linux. TempFilePath1 package com.mkyong.io.temp; public class TempFilePath1 { public static void main(String[] args) { String tmpdir …

Read more

How to write to file in Java – FileOutputStream

In Java, FileOutputStream is a bytes stream class that’s used to handle raw binary data. To write the data to file, you have to convert the data into bytes and save it to file. See below full example. package com.mkyong.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteFileExample { public static void main(String[] args) …

Read more

How to set the file permission in Java

In Java, file permissions are very OS specific: *nix , NTFS (windows) and FAT/FAT32, all have different kind of file permissions. Java comes with some generic file permission to deal with it. Check if the file permission allow : file.canExecute(); – return true, file is executable; false is not. file.canWrite(); – return true, file is …

Read more

How to create a file in Java

In Java, there are many ways to create and write to a file. Files.newBufferedWriter (Java 8) Files.write (Java 7) PrintWriter File.createNewFile Note I prefer the Java 7 nio Files.write to create and write to a file, because it has much cleaner code and auto close the opened resources. Files.write( Paths.get(fileName), data.getBytes(StandardCharsets.UTF_8)); 1. Java 8 Files.newBufferedWriter …

Read more

How to determine a prime number in Java

A very important question in mathematics and security is telling whether a number is prime or not. This is pretty useful when encrypting a password. In this tutorial, you will learn how to find whether a number is prime in simple cases. Trivial Cases We learned numbers are prime if the only divisors they have …

Read more

Java – How to save byte[] to a file

This article shows a few ways to save a byte[] into a file. For JDK 1.7 and above, the NIO Files.write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths.get("/path/file"); Files.write(path, bytes); FileOutputStream is the best alternative. try (FileOutputStream fos = new FileOutputStream("/path/file")) { fos.write(bytes); //fos.close …

Read more

Java – How to convert File to byte[]

In Java, we can use Files.readAllBytes(path) to convert a File object into a byte[]. import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; String filePath = "/path/to/file"; // file to byte[], Path byte[] bytes = Files.readAllBytes(Paths.get(filePath)); // file to byte[], File -> Path File file = new File(filePath); byte[] bytes = Files.readAllBytes(file.toPath()); P.S The NIO Files class is …

Read more

Quartz 1.6 scheduler tutorial

Quartz is a powerful and advance scheduler framework, to help Java developer to scheduler a job to run at a specified date and time. This tutorial show you how to develop a scheduler job using Quartz 1.6.3. Note This example is a bit outdate, unless you are still using the old Quartz 1.6.3 library, otherwise, …

Read more