Reorganized network appendix. try-with-finally reformatting

This commit is contained in:
Bruce Eckel 2016-09-06 12:32:51 -06:00
parent 13a6e2c5e6
commit 073f20e221
44 changed files with 438 additions and 324 deletions

View File

@ -50,9 +50,11 @@ extends AbstractProcessor {
}
private void
writeInterfaceFile(String interfaceName) {
try(Writer writer = processingEnv.getFiler()
.createSourceFile(interfaceName)
.openWriter()) {
try(
Writer writer = processingEnv.getFiler()
.createSourceFile(interfaceName)
.openWriter()
) {
String packageName = elementUtils
.getPackageOf(interfaceMethods
.get(0)).toString();

View File

@ -17,21 +17,25 @@ public class GZIPcompress {
"the file to test.gz");
System.exit(1);
}
try(InputStream in = new BufferedInputStream(
new FileInputStream(args[0]));
BufferedOutputStream out =
new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream("test.gz")))) {
try(
InputStream in = new BufferedInputStream(
new FileInputStream(args[0]));
BufferedOutputStream out =
new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream("test.gz")))
) {
System.out.println("Writing file");
int c;
while((c = in.read()) != -1)
out.write(c);
}
System.out.println("Reading file");
try(BufferedReader in2 = new BufferedReader(
new InputStreamReader(new GZIPInputStream(
new FileInputStream("test.gz"))))) {
try(
BufferedReader in2 = new BufferedReader(
new InputStreamReader(new GZIPInputStream(
new FileInputStream("test.gz"))))
) {
String s;
while((s = in2.readLine()) != null)
System.out.println(s);

View File

@ -13,19 +13,23 @@ import java.util.*;
public class ZipCompress {
public static void
main(String[] args) throws IOException {
try(FileOutputStream f =
new FileOutputStream("test.zip");
CheckedOutputStream csum =
new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out =
new BufferedOutputStream(zos)) {
try(
FileOutputStream f =
new FileOutputStream("test.zip");
CheckedOutputStream csum =
new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out =
new BufferedOutputStream(zos)
) {
zos.setComment("A test of Java Zipping");
// No corresponding getComment(), though.
for(String arg : args) {
System.out.println("Writing file " + arg);
try(InputStream in = new BufferedInputStream(
new FileInputStream(arg))) {
try(
InputStream in = new BufferedInputStream(
new FileInputStream(arg))
) {
zos.putNextEntry(new ZipEntry(arg));
int c;
while((c = in.read()) != -1)
@ -39,13 +43,15 @@ public class ZipCompress {
}
// Now extract the files:
System.out.println("Reading file");
try(FileInputStream fi =
new FileInputStream("test.zip");
CheckedInputStream csumi =
new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis =
new BufferedInputStream(in2)) {
try(
FileInputStream fi =
new FileInputStream("test.zip");
CheckedInputStream csumi =
new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis =
new BufferedInputStream(in2)
) {
ZipEntry ze;
while((ze = in2.getNextEntry()) != null) {
System.out.println("Reading file " + ze);
@ -58,7 +64,9 @@ public class ZipCompress {
"Checksum: "+csumi.getChecksum().getValue());
}
// Alternative way to open and read Zip files:
try(ZipFile zf = new ZipFile("test.zip")) {
try(
ZipFile zf = new ZipFile("test.zip")
) {
Enumeration e = zf.entries();
while(e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry)e.nextElement();

View File

@ -18,8 +18,10 @@ class Second extends Reporter {}
public class AutoCloseableDetails {
public static void main(String[] args) {
try(First f = new First();
Second s = new Second()) {
try(
First f = new First();
Second s = new Second()
) {
}
}
}

View File

@ -7,8 +7,10 @@ class Third extends Reporter {}
public class BodyException {
public static void main(String[] args) {
try(First f = new First();
Second s2 = new Second()) {
try(
First f = new First();
Second s2 = new Second()
) {
System.out.println("In body");
Third t = new Third();
new SecondExcept();

View File

@ -25,9 +25,11 @@ class Closer extends Reporter2 {
public class CloseExceptions {
public static void main(String[] args) {
try(First f = new First();
Closer c = new Closer();
Second s = new Second()) {
try(
First f = new First();
Closer c = new Closer();
Second s = new Second()
) {
System.out.println("In body");
} catch(CloseException e) {
System.out.println("Caught: " + e);

View File

@ -14,9 +14,11 @@ class SecondExcept extends Reporter {
public class ConstructorException {
public static void main(String[] args) {
try(First f = new First();
SecondExcept s = new SecondExcept();
Second s2 = new Second()) {
try(
First f = new First();
SecondExcept s = new SecondExcept();
Second s2 = new Second()
) {
System.out.println("In body");
} catch(CE e) {
System.out.println("Caught: " + e);

View File

@ -9,10 +9,12 @@ import java.util.stream.*;
public class StreamsAreAutoCloseable {
public static void
main(String[] args) throws IOException{
try(Stream<String> in = Files.lines(
Paths.get("StreamsAreAutoCloseable.java"));
PrintWriter outfile = new PrintWriter(
"Results.txt");) { // (1)
try(
Stream<String> in = Files.lines(
Paths.get("StreamsAreAutoCloseable.java"));
PrintWriter outfile = new PrintWriter(
"Results.txt"); // (1)
) {
in.skip(5)
.limit(1)
.map(String::toLowerCase)

View File

@ -8,7 +8,9 @@ class Anything {}
public class TryAnything {
public static void main(String[] args) {
try(Anything a = new Anything()) {
try(
Anything a = new Anything()
) {
}
}
}

View File

@ -6,8 +6,10 @@ import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
try(InputStream in = new FileInputStream(
new File("TryWithResources.java"))) {
try(
InputStream in = new FileInputStream(
new File("TryWithResources.java"))
) {
int contents = in.read();
// Process contents
} catch(IOException e) {

View File

@ -8,10 +8,12 @@ import java.util.stream.*;
public class StreamInAndOut {
public static void main(String[] args) {
try(Stream<String> input =
Files.lines(Paths.get("StreamInAndOut.java"));
PrintWriter output =
new PrintWriter("StreamInAndOut.txt")) {
try(
Stream<String> input =
Files.lines(Paths.get("StreamInAndOut.java"));
PrintWriter output =
new PrintWriter("StreamInAndOut.txt")
) {
input
.map(String::toUpperCase)
.forEachOrdered(output::println);

View File

@ -9,12 +9,14 @@ public class BasicFileOutput {
static String file = "BasicFileOutput.dat";
public static void
main(String[] args) throws IOException {
try(BufferedReader in = new BufferedReader(
new StringReader(
BufferedInputFile.read(
"BasicFileOutput.java")));
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(file)))) {
try(
BufferedReader in = new BufferedReader(
new StringReader(
BufferedInputFile.read(
"BasicFileOutput.java")));
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(file)))
) {
int lineCount = 1;
String s;
while((s = in.readLine()) != null )

View File

@ -8,8 +8,10 @@ import java.io.*;
public class BufferedInputFile {
public static String
read(String filename) throws IOException {
try(BufferedReader in = new BufferedReader(
new FileReader(filename))) {
try(
BufferedReader in = new BufferedReader(
new FileReader(filename))
) {
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null)

View File

@ -9,11 +9,13 @@ public class FileOutputShortcut {
static String file = "FileOutputShortcut.dat";
public static void
main(String[] args) throws IOException {
try(BufferedReader in = new BufferedReader(
new StringReader(BufferedInputFile.read(
"FileOutputShortcut.java")));
// Here's the shortcut:
PrintWriter out = new PrintWriter(file)) {
try(
BufferedReader in = new BufferedReader(
new StringReader(BufferedInputFile.read(
"FileOutputShortcut.java")));
// Here's the shortcut:
PrintWriter out = new PrintWriter(file)
) {
int lineCount = 1;
String s;
while((s = in.readLine()) != null )

View File

@ -8,11 +8,13 @@ import java.io.*;
public class FormattedMemoryInput {
public static void
main(String[] args) throws IOException {
try(DataInputStream in = new DataInputStream(
new ByteArrayInputStream(
BufferedInputFile.read(
"FormattedMemoryInput.java")
.getBytes()))) {
try(
DataInputStream in = new DataInputStream(
new ByteArrayInputStream(
BufferedInputFile.read(
"FormattedMemoryInput.java")
.getBytes()))
) {
while(true)
System.out.write((char)in.readByte());
} catch(EOFException e) {

View File

@ -7,17 +7,21 @@ import java.io.*;
public class StoringAndRecoveringData {
public static void
main(String[] args) throws IOException {
try(DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("Data.txt")))) {
try(
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("Data.txt")))
) {
out.writeDouble(3.14159);
out.writeUTF("That was pi");
out.writeDouble(1.41413);
out.writeUTF("Square root of 2");
}
try(DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("Data.txt")))) {
try(
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("Data.txt")))
) {
System.out.println(in.readDouble());
// Only readUTF() will recover the
// Java-UTF String properly:

View File

@ -9,9 +9,11 @@ import java.io.*;
public class TestEOF {
public static void
main(String[] args) throws IOException {
try(DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("TestEOF.java")))) {
try(
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("TestEOF.java")))
) {
while(in.available() != 0)
System.out.write(in.readByte());
}

View File

@ -7,8 +7,10 @@ import java.io.*;
public class UsingRandomAccessFile {
static String file = "rtest.dat";
static void display() throws IOException {
try(RandomAccessFile rf =
new RandomAccessFile(file, "r")) {
try(
RandomAccessFile rf =
new RandomAccessFile(file, "r")
) {
for(int i = 0; i < 7; i++)
System.out.println(
"Value " + i + ": " + rf.readDouble());
@ -17,16 +19,20 @@ public class UsingRandomAccessFile {
}
public static void
main(String[] args) throws IOException {
try(RandomAccessFile rf =
new RandomAccessFile(file, "rw")) {
try(
RandomAccessFile rf =
new RandomAccessFile(file, "rw")
) {
for(int i = 0; i < 7; i++)
rf.writeDouble(i*1.414);
rf.writeUTF("The end of the file");
rf.close();
display();
}
try(RandomAccessFile rf =
new RandomAccessFile(file, "rw")) {
try(
RandomAccessFile rf =
new RandomAccessFile(file, "rw")
) {
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();

View File

@ -2,31 +2,22 @@
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// {ValidateByHand}
// Tests the ChatterServer by starting multiple
// clients, each of which sends datagrams.
// Starts multiple clients, each of which sends datagrams.
package network;
import java.net.*;
import java.io.*;
import onjava.*;
public class ChatterClient extends Thread {
public class ChatterClient implements Runnable {
private InetAddress hostAddress;
private byte[] buf = new byte[1000];
private DatagramPacket dp =
new DatagramPacket(buf, buf.length);
private int id;
private static int counter = 0;
private int id = counter++;
public ChatterClient(int identifier) {
id = identifier;
try {
hostAddress =
InetAddress.getByName("localhost");
} catch(UnknownHostException e) {
System.err.println("Cannot find host");
System.exit(1);
}
System.out.println("ChatterClient starting");
public ChatterClient(InetAddress hostAddress) {
this.hostAddress = hostAddress;
System.out.println("ChatterClient #" + id + " starting");
}
public void sendAndEcho(String msg) {
try (
@ -45,21 +36,13 @@ public class ChatterClient extends Thread {
dp.getPort() + ": " +
Dgram.toString(dp);
System.out.println(rcvd);
} catch(SocketException e) {
System.err.println("Can't open socket");
throw new RuntimeException(e);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
for(int i = 0; i <= 25; i++)
for(int i = 0; i <= 5; i++)
sendAndEcho("Client #" + id + ", message #" + i);
}
public static void main(String[] args) {
new TimedAbort(5); // Terminate after 5 seconds
for(int i = 0; i <= 10; i++)
new ChatterClient(i).start();
}
}

View File

@ -2,20 +2,18 @@
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// {ValidateByHand}
// A server that echoes datagrams
package network;
import java.net.*;
import java.io.*;
import onjava.*;
public class ChatterServer {
public class ChatterServer implements Runnable {
static final int INPORT = 1711;
private byte[] buf = new byte[1000];
private DatagramPacket dp =
new DatagramPacket(buf, buf.length);
public ChatterServer() {
public void run() {
// Can listen & send on the same socket:
try (
DatagramSocket socket = new DatagramSocket(INPORT)
@ -38,13 +36,6 @@ public class ChatterServer {
dp.getAddress(), dp.getPort());
socket.send(echo);
}
} catch(IOException e) {
System.out.println("Communication error");
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new TimedAbort(5); // Terminate after 5 seconds
new ChatterServer();
} catch(IOException e) { throw new RuntimeException(e); }
}
}

View File

@ -1,18 +1,18 @@
// network/MultiSimpleServer.java
// network/MultiServer.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Uses threads to handle any number of clients.
// {ValidateByHand}
package network;
import java.io.*;
import java.net.*;
import onjava.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class ServeOneSimple implements Runnable {
class ServeOne implements Runnable {
private ServerSocket ss;
public
ServeOneSimple(ServerSocket ss) throws IOException {
static final int PORT = 8080;
public ServeOne(ServerSocket ss) throws IOException {
this.ss = ss;
}
@Override
@ -27,33 +27,34 @@ class ServeOneSimple implements Runnable {
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
// Enable auto-flush:
// Boolean enables auto-flush
socket.getOutputStream())), true)
) {
while (true) {
String str = in.readLine();
if(str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
System.out.println("closing socket...");
in.lines().anyMatch(message -> {
if (message.equals("END")) {
System.out.println("Received END. Closing Socket.");
return true;
}
System.out.println("Message : " + message);
out.println(message);
return false;
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class MultiSimpleServer {
static final int PORT = 8080;
public static void
main(String[] args) throws IOException {
new TimedAbort(5); // Terminate after 5 seconds
System.out.println("Server Started");
try (ServerSocket ss = new ServerSocket(PORT)){
// Block until a connection occurs:
while(true) {
new ServeOneSimple(ss);
public class MultiServer implements Runnable {
private ExecutorService pool;
public void run() {
pool = Executors.newFixedThreadPool(30);
try (ServerSocket ss = new ServerSocket(ServeOne.PORT)) {
while (true) {
pool.submit(new ServeOne(ss));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -4,22 +4,19 @@
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Sends lines to the server and
// reads lines the server sends.
// {ValidateByHand}
package network;
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void
main(String[] args) throws IOException {
// Produce the "Local Loopback" IP address
// for testing on one machine w/o a network:
InetAddress addr =
InetAddress.getLoopbackAddress();
System.out.println("addr = " + addr);
// TWR will sure that the socket is closed:
public class SimpleClient implements Runnable {
private InetAddress hostAddress;
public SimpleClient(InetAddress hostAddress) {
this.hostAddress = hostAddress;
}
public void run() {
System.out.println("hostAddress = " + hostAddress);
try (
Socket socket = new Socket(addr, SimpleServer.PORT);
Socket socket = new Socket(hostAddress, SimpleServer.PORT);
BufferedReader in =
new BufferedReader(
new InputStreamReader(
@ -35,9 +32,11 @@ public class SimpleClient {
for(int i = 0; i < 10; i ++) {
out.println("hello " + i);
String str = in.readLine();
System.out.println(str);
System.out.println("client Message : " + str);
}
out.println("END");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -1,15 +1,12 @@
// network/MultiSimpleClient.java
// network/SimpleClient2.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Testing MultiSimpleServer with multiple clients.
// {ValidateByHand}
package network;
import java.net.*;
import java.io.*;
import onjava.*;
class SimpleClientThread implements Runnable {
public class SimpleClient2 implements Runnable {
private InetAddress address;
private static int counter = 0;
private int id = counter++;
@ -17,7 +14,7 @@ class SimpleClientThread implements Runnable {
public static int threadCount() {
return threadcount;
}
public SimpleClientThread(InetAddress address) {
public SimpleClient2(InetAddress address) {
System.out.println("Making client " + id);
this.address = address;
threadcount++;
@ -26,7 +23,7 @@ class SimpleClientThread implements Runnable {
public void run() {
try (
Socket socket =
new Socket(address, MultiSimpleServer.PORT);
new Socket(address, ServeOne.PORT);
BufferedReader in =
new BufferedReader(
new InputStreamReader(
@ -51,18 +48,3 @@ class SimpleClientThread implements Runnable {
}
}
}
public class MultiSimpleClient {
static final int MAX_THREADS = 40;
public static void
main(String[] args) throws IOException,
InterruptedException {
new TimedAbort(5); // Terminate after 5 seconds
InetAddress address = InetAddress.getByName(null);
while(true) {
if(SimpleClientThread.threadCount() < MAX_THREADS)
new SimpleClientThread(address);
Thread.sleep(100);
}
}
}

View File

@ -3,24 +3,23 @@
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
// Echoes what the client sends.
// {ValidateByHand}
package network;
import java.io.*;
import java.net.*;
public class SimpleServer {
public class SimpleServer implements Runnable {
// Choose a port outside of the range 1-1024:
public static final int PORT = 8080;
public static void
main(String[] args) throws IOException {
public void run() {
try (
ServerSocket s = new ServerSocket(PORT);
// Blocks until a connection occurs:
Socket socket = s.accept();
BufferedReader in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
PrintWriter out =
new PrintWriter(
new BufferedWriter(
@ -29,12 +28,17 @@ public class SimpleServer {
socket.getOutputStream())), true)
) {
System.out.println("Connection: " + socket);
while (true) {
String str = in.readLine();
if(str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
in.lines().anyMatch(message->{
if (message.equals("END")) {
System.out.println("Received END. Closing Socket.");
return true;
}
System.out.println("Server Response: " + message);
out.println(message);
return false;
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,21 @@
// network/tests/ChatterTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.net.*;
import org.junit.jupiter.api.*;
public class ChatterTest {
@BeforeAll
static void startMsg() {
System.out.println(">>> ChatterTest");
}
@Test
void chatterTest() throws Exception {
// <* These need to be handed to an executor: *>
new ChatterServer();
new ChatterClient(InetAddress.getLocalHost());
// No exceptions means success
}
}

View File

@ -0,0 +1,26 @@
// network/tests/MultiTest.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.net.*;
import org.junit.jupiter.api.*;
public class MultiTest {
@BeforeAll
static void startMsg() {
System.out.println(">>> MultiClientTest");
}
@Test
void multiTest() throws Exception {
final int MAX_THREADS = 40;
new MultiServer();
InetAddress address = InetAddress.getByName(null);
while(true) {
if(SimpleClient2.threadCount() < MAX_THREADS)
new SimpleClient2(address);
Thread.sleep(100);
}
// No exceptions mean success
}
}

View File

@ -1,45 +0,0 @@
// network/tests/SimpleTcpTests.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.util.*;
import java.util.stream.*;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
import onjava.*;
public class SimpleTcpTests {
@BeforeAll
static void startMsg() {
System.out.println(">>> Network Tests <<<");
}
@BeforeEach
void setupServer () { }
@Test
void basicTest() throws Exception {
SimpleServer server = new SimpleServer();
SimpleClient client = new SimpleClient();
client.main(null);
assertTrue(false); // Fail until there are good assertions in the test
}
@Test
void multiTest() throws Exception {
MultiSimpleClient client = new MultiSimpleClient();
MultiSimpleServer server = new MultiSimpleServer();
client.main(null);
assertTrue(false); // Fail until there are good assertions in the test
}
@Test
void chatterTest() throws Exception {
ChatterServer server = new ChatterServer();
ChatterClient.main(null);
assertTrue(false); // Fail until there are good assertions in the test
}
}

View File

@ -0,0 +1,20 @@
// network/tests/TestSimpleServerClient.java
// (c)2016 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
package network;
import java.net.*;
import org.junit.jupiter.api.*;
public class TestSimpleServerClient {
@BeforeAll
static void startMsg() {
System.out.println(">>> TestSimpleServerClient");
}
@Test
void basicTest() throws Exception {
SimpleServer server = new SimpleServer();
SimpleClient client = new SimpleClient(InetAddress.getLocalHost());
// Success if no exceptions happen
}
}

View File

@ -12,13 +12,17 @@ public class BufferToText {
private static final int BSIZE = 1024;
public static void
main(String[] args) throws Exception {
try(FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()) {
try(
FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(ByteBuffer.wrap("Some text".getBytes()));
}
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
try(FileChannel fc = new FileInputStream(
"data2.txt").getChannel()) {
try(
FileChannel fc = new FileInputStream(
"data2.txt").getChannel()
) {
fc.read(buff);
}
buff.flip();
@ -30,15 +34,19 @@ public class BufferToText {
System.out.println("Decoded using " + encoding + ": "
+ Charset.forName(encoding).decode(buff));
// Or, we could encode with something that prints:
try(FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()) {
try(
FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(ByteBuffer.wrap(
"Some text".getBytes("UTF-16BE")));
}
// Now try reading again:
buff.clear();
try(FileChannel fc = new FileInputStream(
"data2.txt").getChannel()) {
try(
FileChannel fc = new FileInputStream(
"data2.txt").getChannel()
) {
fc.read(buff);
}
buff.flip();
@ -46,14 +54,18 @@ public class BufferToText {
// Use a CharBuffer to write through:
buff = ByteBuffer.allocate(24); // More than needed
buff.asCharBuffer().put("Some text");
try(FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()) {
try(
FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(buff);
}
// Read and display:
buff.clear();
try(FileChannel fc = new FileInputStream(
"data2.txt").getChannel()) {
try(
FileChannel fc = new FileInputStream(
"data2.txt").getChannel()
) {
fc.read(buff);
}
buff.flip();

View File

@ -17,10 +17,12 @@ public class ChannelCopy {
"arguments: sourcefile destfile");
System.exit(1);
}
try(FileChannel in = new FileInputStream(
args[0]).getChannel();
FileChannel out = new FileOutputStream(
args[1]).getChannel()) {
try(
FileChannel in = new FileInputStream(
args[0]).getChannel();
FileChannel out = new FileOutputStream(
args[1]).getChannel()
) {
ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
while(in.read(buffer) != -1) {
buffer.flip(); // Prepare for writing

View File

@ -9,9 +9,11 @@ import java.io.*;
public class FileLocking {
public static void
main(String[] args) throws Exception {
try(FileOutputStream fos =
new FileOutputStream("file.txt");
FileLock fl = fos.getChannel().tryLock()) {
try(
FileOutputStream fos =
new FileOutputStream("file.txt");
FileLock fl = fos.getChannel().tryLock()
) {
if(fl != null) {
System.out.println("Locked File");
TimeUnit.MILLISECONDS.sleep(100);

View File

@ -11,8 +11,10 @@ public class LargeMappedFiles {
static int length = 0x8000000; // 128 MB
public static void
main(String[] args) throws Exception {
try(RandomAccessFile tdat =
new RandomAccessFile("test.dat", "rw")) {
try(
RandomAccessFile tdat =
new RandomAccessFile("test.dat", "rw")
) {
MappedByteBuffer out = tdat.getChannel()
.map(FileChannel.MapMode.READ_WRITE, 0, length);
for(int i = 0; i < length; i++)

View File

@ -15,10 +15,12 @@ public class TransferTo {
"arguments: sourcefile destfile");
System.exit(1);
}
try(FileChannel in = new FileInputStream(
args[0]).getChannel();
FileChannel out = new FileOutputStream(
args[1]).getChannel()) {
try(
FileChannel in = new FileInputStream(
args[0]).getChannel();
FileChannel out = new FileOutputStream(
args[1]).getChannel()
) {
in.transferTo(0, in.size(), out);
// Or:
// out.transferFrom(in, 0, in.size());

View File

@ -13,11 +13,13 @@ public class OSExecute {
try {
Process process =
new ProcessBuilder(command.split(" ")).start();
try(BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream()));
BufferedReader errors = new BufferedReader(
new InputStreamReader(
process.getErrorStream()))) {
try(
BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream()));
BufferedReader errors = new BufferedReader(
new InputStreamReader(
process.getErrorStream()))
) {
String s;
while((s = results.readLine())!= null)
System.out.println(s);

View File

@ -47,18 +47,22 @@ public class Compete {
for(int i = 0; i < SIZE; i++)
b[i] = new Thing4();
long t1 = System.currentTimeMillis();
try(ByteArrayOutputStream buf =
new ByteArrayOutputStream();
ObjectOutputStream oos =
new ObjectOutputStream(buf)) {
try(
ByteArrayOutputStream buf =
new ByteArrayOutputStream();
ObjectOutputStream oos =
new ObjectOutputStream(buf)
) {
for(Thing2 a1 : a) {
oos.writeObject(a1);
}
// Now get copies:
try(ObjectInputStream in =
new ObjectInputStream(
new ByteArrayInputStream(
buf.toByteArray()))) {
try(
ObjectInputStream in =
new ObjectInputStream(
new ByteArrayInputStream(
buf.toByteArray()))
) {
Thing2[] c = new Thing2[SIZE];
for(int i = 0; i < SIZE; i++)
c[i] = (Thing2)in.readObject();

View File

@ -87,9 +87,11 @@ public class AStoreCADState {
for(int i = 0; i < 10; i++)
((Shape)shapes.get(i)).setColor(Shape.GREEN);
// Save the state vector:
try(ObjectOutputStream out =
new ObjectOutputStream(
new FileOutputStream("CADState.dat"))) {
try(
ObjectOutputStream out =
new ObjectOutputStream(
new FileOutputStream("CADState.dat"))
) {
out.writeObject(shapeTypes);
Line.serializeStaticState(out);
out.writeObject(shapes);

View File

@ -42,15 +42,19 @@ public class Blip3 implements Externalizable {
System.out.println("Constructing objects:");
Blip3 b3 = new Blip3("A String ", 47);
System.out.println(b3);
try(ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blip3.serialized"))) {
try(
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blip3.serialized"))
) {
System.out.println("Saving object:");
o.writeObject(b3);
}
// Now get it back:
System.out.println("Recovering b3:");
try(ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blip3.serialized"))) {
try(
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blip3.serialized"))
) {
b3 = (Blip3)in.readObject();
}
System.out.println(b3);

View File

@ -44,16 +44,20 @@ public class Blips {
System.out.println("Constructing objects:");
Blip1 b1 = new Blip1();
Blip2 b2 = new Blip2();
try(ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blips.serialized"))) {
try(
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Blips.serialized"))
) {
System.out.println("Saving objects:");
o.writeObject(b1);
o.writeObject(b2);
}
// Now get them back:
System.out.println("Recovering b1:");
try(ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blips.serialized"))) {
try(
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Blips.serialized"))
) {
b1 = (Blip1)in.readObject();
}
// OOPS! Throws an exception:

View File

@ -24,14 +24,18 @@ public class Logon implements Serializable {
main(String[] args) throws Exception {
Logon a = new Logon("Hulk", "myLittlePony");
System.out.println("logon a = " + a);
try(ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Logon.dat"))) {
try(
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("Logon.dat"))
) {
o.writeObject(a);
}
TimeUnit.SECONDS.sleep(1); // Delay
// Now get them back:
try(ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Logon.dat"))) {
try(
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("Logon.dat"))
) {
System.out.println(
"Recovering object at " + new Date());
a = (Logon)in.readObject();

View File

@ -31,27 +31,33 @@ public class MyWorld {
animals.add(new Animal("Ralph the hamster", house));
animals.add(new Animal("Molly the cat", house));
System.out.println("animals: " + animals);
try(ByteArrayOutputStream buf1 =
new ByteArrayOutputStream();
ObjectOutputStream o1 =
new ObjectOutputStream(buf1)) {
try(
ByteArrayOutputStream buf1 =
new ByteArrayOutputStream();
ObjectOutputStream o1 =
new ObjectOutputStream(buf1)
) {
o1.writeObject(animals);
o1.writeObject(animals); // Write a 2nd set
// Write to a different stream:
try(ByteArrayOutputStream buf2 =
new ByteArrayOutputStream();
ObjectOutputStream o2 =
new ObjectOutputStream(buf2)) {
try(
ByteArrayOutputStream buf2 =
new ByteArrayOutputStream();
ObjectOutputStream o2 =
new ObjectOutputStream(buf2)
) {
o2.writeObject(animals);
// Now get them back:
try(ObjectInputStream in1 =
new ObjectInputStream(
new ByteArrayInputStream(
buf1.toByteArray()));
ObjectInputStream in2 =
new ObjectInputStream(
new ByteArrayInputStream(
buf2.toByteArray()))) {
try(
ObjectInputStream in1 =
new ObjectInputStream(
new ByteArrayInputStream(
buf1.toByteArray()));
ObjectInputStream in2 =
new ObjectInputStream(
new ByteArrayInputStream(
buf2.toByteArray()))
) {
List
animals1 = (List)in1.readObject(),
animals2 = (List)in1.readObject(),

View File

@ -11,9 +11,11 @@ public class RecoverCADState {
@SuppressWarnings("unchecked")
public static void
main(String[] args) throws Exception {
try(ObjectInputStream in =
new ObjectInputStream(
new FileInputStream("CADState.dat"))) {
try(
ObjectInputStream in =
new ObjectInputStream(
new FileInputStream("CADState.dat"))
) {
// Read in the same order they were written:
List<Class<? extends Shape>> shapeTypes =
(List<Class<? extends Shape>>)in.readObject();

View File

@ -51,27 +51,35 @@ public class Worm implements Serializable {
IOException {
Worm w = new Worm(6, 'a');
System.out.println("w = " + w);
try(ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("worm.dat"))) {
try(
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("worm.dat"))
) {
out.writeObject("Worm storage\n");
out.writeObject(w);
}
try(ObjectInputStream in = new ObjectInputStream(
new FileInputStream("worm.dat"))) {
try(
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("worm.dat"))
) {
String s = (String)in.readObject();
Worm w2 = (Worm)in.readObject();
System.out.println(s + "w2 = " + w2);
}
try(ByteArrayOutputStream bout =
new ByteArrayOutputStream();
ObjectOutputStream out2 =
new ObjectOutputStream(bout)) {
try(
ByteArrayOutputStream bout =
new ByteArrayOutputStream();
ObjectOutputStream out2 =
new ObjectOutputStream(bout)
) {
out2.writeObject("Worm storage\n");
out2.writeObject(w);
out2.flush();
try(ObjectInputStream in2 = new ObjectInputStream(
new ByteArrayInputStream(
bout.toByteArray()))) {
try(
ObjectInputStream in2 = new ObjectInputStream(
new ByteArrayInputStream(
bout.toByteArray()))
) {
String s = (String)in2.readObject();
Worm w3 = (Worm)in2.readObject();
System.out.println(s + "w3 = " + w3);

View File

@ -9,11 +9,13 @@ public class Redirecting {
public static void
main(String[] args) throws IOException {
PrintStream console = System.out;
try(BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("Redirecting.txt")))) {
try(
BufferedInputStream in = new BufferedInputStream(
new FileInputStream("Redirecting.java"));
PrintStream out = new PrintStream(
new BufferedOutputStream(
new FileOutputStream("Redirecting.txt")))
) {
System.setIn(in);
System.setOut(out);
System.setErr(out);

View File

@ -75,3 +75,27 @@ public class CountedListTest {
"An", "African", "Swallow" });
}
}
/* Output:
>>> Starting CountedListTest
CountedList #0
Set up for 0
Running testRemove()
Cleaning up 0
CountedList #1
Set up for 1
Running testReplace()
Cleaning up 1
CountedList #2
Set up for 2
Running testAddAll()
Cleaning up 2
CountedList #3
Set up for 3
Running testInsert()
Cleaning up 3
CountedList #4
Set up for 4
Running testOrder()
Cleaning up 4
>>> Finished CountedListTest
*/