Java Input Output
This tutorial explains how to read and write files via Java.
Table of Contents
Java provides a standard way of reading from and writing to files. Traditionally the java.io
package was used, but in modern Java applications you use the java.nio.file
API.
Java will read all input as a stream of bytes. The InputStream
class is the superclass of all classes representing an input stream of bytes.
To read a text file you can use the Files.readAllBytes
method as demonstrated by the following listing.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// somewhere in your code
String content = new String(Files.readAllBytes(Paths.get(fileName)));
To read a text file line by line into a List
of type String
structure you can use the following example.
List<String> lines = Files.readAllLines(Paths.get(fileName));
To write a file you can use the following method:
Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE);
Create a new Java project called com.vogella.java.files. Create the following FilesUtil.java
class.
package com.vogella.java.files; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; public class FilesUtil { public static String readTextFile(String fileName) throws IOException { String content = new String(Files.readAllBytes(Paths.get(fileName))); return content; } public static List<String> readTextFileByLines(String fileName) throws IOException { List<String> lines = Files.readAllLines(Paths.get(fileName)); return lines; } public static void writeToTextFile(String fileName, String content) throws IOException { Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE); } }
To test these methods, create a text file called file.txt
with some content in your project folder. Create the following Main
class and run it.
package com.vogella.java.files; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws IOException { String input = FilesUtil.readTextFile("file.txt"); System.out.println(input); FilesUtil.writeToTextFile("copy.txt", input); System.out.println(FilesUtil.readTextFile("copy.txt")); FilesUtil.readTextFileByLines("file.txt"); Path path = Paths.get("file.txt"); } }