Core Java Advanced LiveLessons

Processing Input and Output

Copyright © Cay S. Horstmann 2016

Understand the concept of input/output streams

Input/Output Streams

Obtaining Streams

Reading Bytes

Writing Bytes

Read and write text files

Character Encodings

Text Input

jshell

import java.nio.file.*;
import java.nio.charset.*;

Files.readAllLines(Paths.get("poem.txt"), StandardCharsets.UTF_8)
Files.readAllLines(Paths.get("poem-win1252.txt"), StandardCharsets.UTF_8)
    // Throws MalformedInputException
Files.readAllLines(Paths.get("poem-win1252.txt"), Charset.forName("windows-1252"))
    // Ok
Files.readAllLines(Paths.get("poem.txt"), Charset.forName("windows-1252"))
    // Looks weird

Reading Tokens

jshell

import java.nio.file.*;
import java.nio.charset.*;

Scanner in = new Scanner(Paths.get("poem.txt"), "UTF-8");
while (in.hasNext()) System.out.println(in.next());

// Now try again with
in.useDelimiter("\\PL+");

Text Output

jshell

import java.nio.file.*;
import java.nio.charset.*;

PrintWriter out = new PrintWriter("test.txt", "UTF-8")
for (int i = 1; i <= 100; i++) out.printf("%6d%n", i * i);
    // Now open another console and type cat squares.txt
out.close();
    // In the other console, type cat squares.txt

String Writers

jshell

StringWriter writer = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(writer));
writer.toString()

Work with binary data

Reading and Writing Binary Data

Random Access Files

lesson03/randomAccess

Memory-Mapped Files

lesson03/memoryMap

java memoryMap.MemoryMapTest /opt/jdk1.8.0/src.zip 
java memoryMap.MemoryMapTest2 /opt/jdk1.8.0/src.zip 

Create, access, and delete files and directories

Paths

Working with Paths

Taking Paths Apart

jshell

import java.nio.file.*;
Path p = Paths.get(".")
p = p.toAbsolutePath()
p.resolve("../lesson2")
p.resolve("../lesson2").normalize()
p.getParent()
p.getFileName()
p.getRoot()
p.getName(0)
p.getNameCount()

Creating Files and Directories

Checking File Properties

Copying, Moving, and Deleting Files

Visiting Directory Entries

jshell

Files.list(Paths.get("../..")).forEach(System.out::println)
Files.walk(Paths.get("../..")).forEach(System.out::println)
Files.find(Paths.get("../.."), Integer.MAX_VALUE,
    (p, attr) -> attr.size() > 100000).forEach(System.out::println)

Copying and Deleting Directory Trees

Zip Files

jshell

Path p = Paths.get("/opt/jdk1.8.0/src.zip")
FileSystem zipfs = FileSystems.newFileSystem(p, null)
Files.walk(zipfs.getPath("/")).limit(100).forEach(System.out::println)
Files.copy(zipfs.getPath("/java/lang/String.java"), Paths.get("/tmp/String.java"));

Path zipPath = Paths.get("/tmp/myfile.zip");
URI uri = new URI("jar", zipPath.toUri().toString(), null);
FileSystem zipfs = FileSystems.newFileSystem(uri,
    Collections.singletonMap("create", "true"))
InputStream in = new ByteArrayInputStream("Hello".getBytes("UTF-8"));
Files.copy(in, zipfs.getPath("/hello.txt"))
zipfs.close();

Process data from the internet

URLs and URL Connections

The Five Stages of URL Connections

  1. Get an URLConnection object:
    URLConnection connection = url.openConnection();
  2. Set request properties:
    connection.setRequestProperty("Accept-Charset", "UTF-8, ISO-8859-1");
  3. Send data to the server:
    connection.setDoOutput(true);
    try (OutputStream out = connection.getOutputStream()) { Write to out }
  4. Read the response headers:
    connection.connect(); // If you skipped step 3
    Map<String, List<String>> headers = connection.getHeaderFields();
  5. Read the response:
    try (InputStream in = connection.getInputStream()) { Read from in }

Making a Form Post

lesson03/post

firefox https://www.usps.com/zip4/

java post.PostTest > /tmp/out.html
firefox /tmp/out.html

Work with regular expressions

Regular Expressions

Finding All Matches in a String

jshell

import java.util.regex.*
Matcher matcher = Pattern.compile("[0-9]+").matcher(input)
String input = "9:45am";
while (matcher.find()) System.out.println(matcher.group());

Finding Whether a String Matches

jshell

String regex = "[12]?[0-9]:[0-5][0-9][ap]m";
Pattern.matches(regex, "9:45am")
Pattern.matches(regex, "9:65")

import java.util.stream.*
import java.util.regex.*
import java.nio.file.*

Files.lines(Paths.get("/usr/share/dict/words")).
   filter(Pattern.compile(".+q.+q.+").asPredicate()).
   forEach(System.out::println)

Groups

Splitting Strings

Replacing Matches

Understand the concept of serialization

Serialization

Saving a Serializable Object

Loading a Serializable Object

Serialization Preserves Object References

Tweaking the Serialization Mechanism

objectStream