Many times when developing an application, you need to read or write from files or a network connection. These things are generally referred to as input and output or I/O for short.
In this chapter, we will cover some of the utilities available for I/O within Java and the JVM.
Files
In Java, the
java.io.File class is used to represent files and directories. For example:
1 File file = new File("path/file.txt");
2 File dir = new File("path/"); //directory
Java 7 added several new classes and interfaces for manipulating files and file systems under the java.nio package. This new application program interface (API
) allows developers to access many low-level OS operations that were not available from the Java API before, such as the WatchService and the ability to create links (in Linux/Unix operating systems).
Paths are used to more consistently represent
file or directory paths.
1 Path path = Paths.get("/path/file");
This is shorthand for the following:
1 Path path = FileSystems.getDefault().getPath("/path/file");
The following list defines some of the most important classes and interfaces of the
API:
Files: This class consists exclusively of static methods that operate on files, directories, or other types of files.
Paths: This class consists exclusively of static methods that return a path by converting a path string or URI.
WatchService: An interface for watching various file system events, such as create, delete, and modify.
Reading Files
To read a text file in Java, you can use
BufferedReader
. For example:
1 public void readWithTry() {
2 Charset utf = StandardCharsets.UTF_8;
3 try (BufferedReader reader = Files.newBufferedReader (path, utf)) {
4 for (String line = br.readLine(); line!=null; line = br.readLine())
5 System.out.println(line);
6 } catch (IOException e) {
7 e.printStackTrace();
8 }
9 }
The automatic resource management feature of Java makes dealing with resources, such as files, much easier. Before Java 7, programmers needed to explicitly close all open streams, causing some very verbose code. By using the preceding try statement, BufferedReader will be closed automatically.
However, in Groovy, this can be reduced to one line (leaving out exception handling), as follows:
1 println path.toFile().text
A getText() method
is added to the File class in Groovy that simply reads the whole file. A getBytes() method
is also available for reading bytes from a file.
Writing Files
Writing files is similar to reading them. For writing to text files, you should use
PrintWriter
. It includes the following methods (among others):
print(Object): Prints the given object directly calling toString() on it
println(Object): Prints the given object and then a newline
println(): Prints the newline character sequence
printf(String format, Object...args): Prints a formatted string using the given input
For example, you can use
PrintWriter to easily write to a file as follows:
1 public void printWithTry() {
2 try (FileOutputStream fos = new FileOutputStream("books.txt");
3 PrintWriter pw = new PrintWriter(fos)) {
4 pw.println("Modern Java");
5 } catch (IOException e) {
6 // log the exception
7 }
8 }
There are other ways to output to files, such as
DataOutputStream, for example:
1 public void writeWithTry() {
2 try (FileOutputStream fos = new FileOutputStream("books.txt");
3 DataOutputStream dos = new DataOutputStream(fos)) {
4 dos.writeUTF("Modern Java");
5 } catch (IOException e) {
6 // log the exception
7 }
8 }
DataOutputStream allows an application to write primitive Java data types to an output stream. You can then use DataInputStream to read the data back in. If you’re just dealing with text, you can use PrintWriter and BufferedReader instead.
In Groovy, you can more easily write to files, as follows:
1 new File("books.txt").text = "Modern Java"
2 new File("binary.txt").bytes = "Modern Java".bytes
Groovy adds a setText method and a setBytes to the File class, which allows this syntax to work.
Downloading Files
Although you might not ever do this in practice, it’s fairly simple to download a web page/file in code.
The following Java
code opens an HTTP connection on the given URL (
https://www.google.com, in this case), reads the data into a byte array, and prints out the resulting text.
1 URL url = new URL("https://www.google.com");
2 InputStream input = (InputStream) url.getContent();
3 ByteArrayOutputStream out = new ByteArrayOutputStream();
4 int n = 0;
5 byte[] arr = new byte[1024];
6
7 while (-1 != (n = input.read(arr)))
8 out.write(arr, 0, n);
9
10 System.out.println(new String(out.toByteArray()));
However, in Groovy, this also can be reduced to one line (leaving out exceptions).
1 println "https://www.google.com".toURL().text
A toURL() method
is added to the String class, and a getText() method
is added to the URL class in Groovy.
Summary
After reading this chapter, you should understand how to