Convert object to byte[] in Java

This article shows how to convert an object to byte[] or byte array and vice versa in Java. 1. Convert an object to byte[] The below example show how to use ByteArrayOutputStream and ObjectOutputStream to convert an object to byte[]. // Convert object to byte[] public static byte[] convertObjectToBytes(Object obj) { ByteArrayOutputStream boas = new …

Read more

Java – How to add and remove BOM from UTF-8 file

This article shows you how to add, check and remove the byte order mark (BOM) from a UTF-8 file. The UTF-8 representation of the BOM is the byte sequence 0xEF, 0xBB, 0xBF (hexadecimal), at the beginning of the file. 1. Add BOM to a UTF-8 file 2. Check if a file contains UTF-8 BOM 3. …

Read more

Convert InputStream to BufferedReader in Java

Note The BufferedReader reads characters; while the InputStream is a stream of bytes. The BufferedReader can’t read the InputStream directly; So, we need to use an adapter like InputStreamReader to convert bytes to characters format. For example: // BufferedReader -> InputStreamReader -> InputStream BufferedReader br = new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8)); 1. Reads a file …

Read more

How to get file extension in Java

This article shows how to get the file extension of a file in Java. Topics Get file extension normal Get file extension strict Get file extension hardcode Apache Common IO – FilenameUtils Path: /path/foo.txt -> File Extension: txt Path: . -> File Extension: Path: .. -> File Extension: Path: /path/run.exe -> File Extension: exe Path: …

Read more

Java – Get the name or path of a running JAR file

In Java, we can use the following code snippets to get the path of a running JAR file. // static String jarPath = ClassName.class .getProtectionDomain() .getCodeSource() .getLocation() .toURI() .getPath(); // non-static String jarPath = getClass() .getProtectionDomain() .getCodeSource() .getLocation() .toURI() .getPath(); Sample output. Terminal /home/mkyong/projects/core-java/java-io/target/java-io.jar 1. Get the path of running JAR 1.1 Create an executable …

Read more

Java – Convert File to Path

This article shows how to convert a File to a Path in Java. java.io.File => java.nio.file.Path // Convert File to Path File file = new File("/home/mkyong/test/file.txt"); Path path = file.toPath(); java.nio.file.Path => java.io.File // Convert Path to File Path path = Paths.get("/home/mkyong/test/file.txt"); File file = path.toFile(); 1. Convert File to Path In Java, we can …

Read more

Java – Run shell script on a remote server

This article shows how to use JSch library to run or execute a shell script in a remote server via SSH. pom.xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> 1. Run Remote Shell Script This Java example uses JSch to SSH login a remote server (using password), and runs a shell script hello.sh. 1.1 Here is a …

Read more

File Transfer using SFTP in Java (JSch)

This article shows how to do file transfer from a remote server to the local system and vice versa, using SSH File Transfer Protocol (SFTP) in Java. P.S Tested with JSch 0.1.55 1. JSch Dependency pom.xml <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> 2. File Transfer – JSch Examples 2.1 In JSch, we can use put and …

Read more

How to format FileTime in Java

In Java, we can use DateTimeFormatter to convert the FileTime to other custom date formats. public static String formatDateTime(FileTime fileTime) { LocalDateTime localDateTime = fileTime .toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); return localDateTime.format( DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss")); } 1. File Last Modified Time This example displays the last modified time of a file in a custom date format. GetLastModifiedTime.java package …

Read more

Java – Unable to assign group write permission to a file

In Java, we can use the NIO createFile() to assign file permission during file creation. Files.java package java.nio.file; public static Path createFile(Path path, FileAttribute<?>… attrs) throws IOException But, the createFile() fails to assign the group writes file permission to a file on the Unix system? Path path = Paths.get("/home/mkyong/test/runme.sh"); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx"); Files.createFile(path, PosixFilePermissions.asFileAttribute(perms)); …

Read more

How to get file path separator in Java

For file path or directory separator, the Unix system introduced the slash character / as directory separator, and the Microsoft Windows introduced backslash character \ as the directory separator. In a nutshell, this is / on UNIX and \ on Windows. In Java, we can use the following three methods to get the platform-independent file …

Read more

Java Serialization and Deserialization Examples

In Java, Serialization means converting Java objects into a byte stream; Deserialization means converting the serialized object’s byte stream back to the original Java object. Table of contents. 1. Hello World Java Serialization 2. java.io.NotSerializableException 3. What is serialVersionUID? 4. What is transient? 5. Serialize Object to File 6. Why need Serialization in Java? 7. …

Read more

Java – Convert File to String

In Java, we have many ways to convert a File to a String. A text file for testing later. c:\\projects\\app.log A B C D E 1. Java 11 – Files.readString A new method Files.readString is added in java.nio.file.Files, it makes reading a string from File much easier. FileToString1.java package com.mkyong; import java.io.IOException; import java.nio.file.Files; import …

Read more

Java – How to save a String to a File

In Java, there are many ways to write a String to a File. 1. Java 11 – Files.writeString Finally, a new method added in java.nio to save a String into a File easily. StringToFileJava11.java package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class StringToFileJava11 { public static void main(String[] args) …

Read more

How to read a file in Java

This article focus on a few of the commonly used methods to read a file in Java. Files.lines, return a Stream (Java 8) Files.readString, returns a String (Java 11), max file size 2G. Files.readAllBytes, returns a byte[] (Java 7), max file size 2G. Files.readAllLines, returns a List<String> (Java 8) BufferedReader, a classic old friend (Java …

Read more

Java create and write to a file

In Java, we can use Files.write to create and write to a file. String content = "…"; Path path = Paths.get("/home/mkyong/test.txt"); // string -> bytes Files.write(path, content.getBytes(StandardCharsets.UTF_8)); The Files.write also accepts an Iterable interface; it means this API can write a List to a file. List<String> list = Arrays.asList("a", "b", "c"); Files.write(path, list); Short History …

Read more

Java Files.walk examples

The Files.walk API is available since Java 8; it helps to walk a file tree at a given starting path. Topics Files.walk() method signature List all files List all folders or directories Find files by file extension Find files by filename Find files by file size Update all files last modified date 1. Files.walk() method …

Read more

iText – Read and Write PDF in Java

This article talks about reading and writing PDF using iText PDF library. pom.xml <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency> P.S Tested with iTextPdf 5.5.10 1. iText – Write PDF iText PdfWriter example to write content to a PDF file. PdfWriteExample.java package com.mkyong; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class …

Read more

How to read and write Java object to a file

Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization. A Java object is …

Read more

Java – Read a file from resources folder

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream. // the stream holding the file content InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt"); // for static access, uses the class name directly InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt"); The …

Read more

Search directories recursively for file in Java

Here’s an example to show you how to search a file named “post.php” from directory “/Users/mkyong/websites” and all its subdirectories recursively. FileSearch.java package com.mkyong; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSearch { private String fileNameToSearch; private List<String> result = new ArrayList<String>(); public String getFileNameToSearch() { return fileNameToSearch; } public void setFileNameToSearch(String fileNameToSearch) { …

Read more

PrimeFaces : java.io.IOException: Not in GZIP format

Recently, testing on PrimeFaces’ idleMonitor component. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <h:head> </h:head> <h:body> <h1>PrimeFaces and idleMonitor</h1> <p:growl id="messages" showDetail="true" sticky="true" /> <p:idleMonitor timeout="10000" update="messages"> <p:ajax event="idle" listener="#{idleBean.idleListener}" update="messages" /> </p:idleMonitor> </h:body> </html> Problem After 10 seconds, console prompts java.io.IOException: Not in GZIP format? That’s weird, what GZIP to do iwith idleMonitor …

Read more

How to read file in Java – FileInputStream

In Java, we use FileInputStream to read bytes from a file, such as an image file or binary file. Topics FileInputStream – Read a file FileInputStream – Remaining bytes FileInputStream – Better performance FileInputStream vs BufferedInputStream InputStreamReader – Convert FileInputStream to Reader FileInputStream – Read a Unicode file Note However, all the below examples use …

Read more

How to convert InputStream to String in Java

This article shows a few ways to convert an java.io.InputStream to a String. Table of contents 1. ByteArrayOutputStream 2. InputStream#readAllBytes (Java 9) 3. InputStreamReader + StringBuilder 4. InputStreamReader + BufferedReader (modified line breaks) 5. Java 8 BufferedReader#lines (modified line breaks) 6. Apache Commons IO 7. Download Source Code 8. References What are modified line breaks? …

Read more

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