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

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

How to find files with the file extension in Java

This article shows how to Java 8 Files.walk to walk a file tree and stream operation filter to find files that match a specific file extension from a folder and its subfolders. // find files matched `png` file extension from folder C:\\test try (Stream<Path> walk = Files.walk(Paths.get("C:\\test"))) { result = walk .filter(p -> !Files.isDirectory(p)) // …

Read more

How to read and write an image in Java

In Java, we can use the javax.imageio.ImageIO class to read and write an image. 1. Read an image Read an image from a file. BufferedImage image = ImageIO.read(new File("c:\\test\\image.png")); Read an image from an URL. BufferedImage image = ImageIO.read(new URL("https://example.com/image.png")); 2. Write or save an image Write or save an image in different image formats. …

Read more

Java – What is serialVersionUID

In Java, serialVersionUID is something like version control, assure both serialized and deserialized objects are using the compatible class. For example, if an object saved into a file (Serialization) with serialVersionUID=1L, when we convert the file back to an object (Derialization), we must use the same serialVersionUID=1L, otherwise an InvalidClassException is thrown. Terminal Exception in …

Read more

How to get the current working directory in Java

In Java, we can use System.getProperty("user.dir") to get the current working directory, the directory from where your program was launched. String dir = System.getProperty("user.dir"); // directory from where the program was launched // e.g /home/mkyong/projects/core-java/java-io System.out.println(dir); One of the good things about this system property user.dir is we can easily override the system property via …

Read more

How to read an object from file in Java (ObjectInputStream)

This example shows how to use ObjectInputStream to read a serialized object from a file in Java, aka Deserialization. public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException { Object result = null; try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { result = ois.readObject(); } return result; } // Convert byte[] to …

Read more

How to write an object to file in Java (ObjectOutputStream)

This example shows how to use ObjectOutputStream to write objects to a file in Java, aka Serialization. public static void writeObjectToFile(Person obj, File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(obj); oos.flush(); } } Note More Java Serialization and Deserialization examples 1. Java object We can …

Read more

How to check if a file exists in Java

In Java, we can use Files.exists(path) to test whether a file exists. The path can be a file or a directory. It is better to combine with !Files.isDirectory(path) to ensure the existing file is not a directory. Path path = Paths.get("/home/mkyong/test/test.log"); // file exists and it is not a directory if(Files.exists(path) && !Files.isDirectory(path)) { System.out.println("File …

Read more

How to convert InputStream to File in Java

Below are some Java examples of converting InputStream to a File. Plain Java – FileOutputStream Apache Commons IO – FileUtils.copyInputStreamToFile Java 7 – Files.copy Java 9 – InputStream.transferTo 1. Plain Java – FileOutputStream This example downloads the google.com HTML page and returns it as an InputStream. And we use FileOutputStream to copy the InputStream into …

Read more

How to convert byte[] to BufferedImage in Java

This article shows how to convert a byte[] to a BufferedImage in Java. InputStream is = new ByteArrayInputStream(bytes); BufferedImage bi = ImageIO.read(is); The idea is puts the byte[] into an ByteArrayInputStream object, and we can use ImageIO.read to convert it to a BufferedImage. 1. Convert byte[] to BufferedImage. The below example shows how to convert …

Read more

How to read a UTF-8 file in Java

In Java, the InputStreamReader accepts a charset to decode the byte streams into character streams. We can pass a StandardCharsets.UTF_8 into the InputStreamReader constructor to read data from a UTF-8 file. import java.nio.charset.StandardCharsets; //… try (FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(isr) ) { String str; …

Read more

How to write a UTF-8 file in Java

In Java, the OutputStreamWriter accepts a charset to encode the character streams into byte streams. We can pass a StandardCharsets.UTF_8 into the OutputStreamWriter constructor to write data to a UTF-8 file. try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); BufferedWriter writer = new BufferedWriter(osw)) { writer.append(line); } In Java 7+, many …

Read more

How to convert byte[] array to String in Java

In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String. // string to byte[] byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8); // byte[] to string String s = new String(bytes, StandardCharsets.UTF_8); Table of contents 1. byte[] in text and binary data 2. Convert byte[] to String (text data) 3. Convert byte[] to String …

Read more

How to read file in Java – BufferedReader

In this article, we will show you how to use java.io.BufferedReader to read content from a file Note Read this different ways read a file 1. Files.newBufferedReader (Java 8) In Java 8, there is a new method Files.newBufferedReader(Paths.get(“file”)) to return a BufferedReader filename.txt A B C D E FileExample1.java package com.mkyong; import java.io.BufferedReader; import java.io.IOException; …

Read more