Refactor/streamify/fix exceptions

This commit is contained in:
Bruce Eckel 2017-01-21 16:29:16 -08:00
parent f7e0a748d7
commit bf429783f9
15 changed files with 280 additions and 56 deletions

View File

@ -10,13 +10,14 @@ import java.io.*;
public class BufferToText {
private static final int BSIZE = 1024;
public static void
main(String[] args) throws Exception {
public static void main(String[] args) {
try(
FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(ByteBuffer.wrap("Some text".getBytes()));
} catch(IOException e) {
throw new RuntimeException(e);
}
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
try(
@ -24,22 +25,28 @@ public class BufferToText {
"data2.txt").getChannel()
) {
fc.read(buff);
} catch(IOException e) {
throw new RuntimeException(e);
}
buff.flip();
// Doesn't work:
System.out.println(buff.asCharBuffer());
// Decode using this system's default Charset:
buff.rewind();
String encoding = System.getProperty("file.encoding");
System.out.println("Decoded using " + encoding + ": "
String encoding =
System.getProperty("file.encoding");
System.out.println("Decoded using " +
encoding + ": "
+ Charset.forName(encoding).decode(buff));
// Or, we could encode with something that prints:
// Encode with something that prints:
try(
FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(ByteBuffer.wrap(
"Some text".getBytes("UTF-16BE")));
} catch(IOException e) {
throw new RuntimeException(e);
}
// Now try reading again:
buff.clear();
@ -48,17 +55,21 @@ public class BufferToText {
"data2.txt").getChannel()
) {
fc.read(buff);
} catch(IOException e) {
throw new RuntimeException(e);
}
buff.flip();
System.out.println(buff.asCharBuffer());
// Use a CharBuffer to write through:
buff = ByteBuffer.allocate(24); // More than needed
buff = ByteBuffer.allocate(24);
buff.asCharBuffer().put("Some text");
try(
FileChannel fc = new FileOutputStream(
"data2.txt").getChannel()
) {
fc.write(buff);
} catch(IOException e) {
throw new RuntimeException(e);
}
// Read and display:
buff.clear();
@ -67,6 +78,8 @@ public class BufferToText {
"data2.txt").getChannel()
) {
fc.read(buff);
} catch(IOException e) {
throw new RuntimeException(e);
}
buff.flip();
System.out.println(buff.asCharBuffer());

View File

@ -10,8 +10,7 @@ import java.io.*;
public class ChannelCopy {
private static final int BSIZE = 1024;
public static void
main(String[] args) throws Exception {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println(
"arguments: sourcefile destfile");
@ -29,6 +28,8 @@ public class ChannelCopy {
out.write(buffer);
buffer.clear(); // Prepare for reading
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -7,8 +7,7 @@ import java.util.concurrent.*;
import java.io.*;
public class FileLocking {
public static void
main(String[] args) throws Exception {
public static void main(String[] args) {
try(
FileOutputStream fos =
new FileOutputStream("file.txt");
@ -20,6 +19,8 @@ public class FileLocking {
fl.release();
System.out.println("Released Lock");
}
} catch(IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}

53
newio/GetChannel.java Normal file
View File

@ -0,0 +1,53 @@
// newio/GetChannel.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Getting channels from streams
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class GetChannel {
private static String name = "data.txt";
private static final int BSIZE = 1024;
public static void main(String[] args) {
// Write a file:
try(
FileChannel fc = new FileOutputStream(name)
.getChannel()
) {
fc.write(ByteBuffer
.wrap("Some text ".getBytes()));
} catch(IOException e) {
throw new RuntimeException(e);
}
// Add to the end of the file:
try(
FileChannel fc = new RandomAccessFile(
name, "rw").getChannel()
) {
fc.position(fc.size()); // Move to the end
fc.write(ByteBuffer
.wrap("Some more".getBytes()));
} catch(IOException e) {
throw new RuntimeException(e);
}
// Read the file:
try(
FileChannel fc = new FileInputStream(name)
.getChannel()
) {
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
while(buff.hasRemaining())
System.out.write(buff.get());
} catch(IOException e) {
throw new RuntimeException(e);
}
System.out.flush();
}
}
/* Output:
Some text Some more
*/

View File

@ -15,8 +15,8 @@ public class LargeMappedFiles {
RandomAccessFile tdat =
new RandomAccessFile("test.dat", "rw")
) {
MappedByteBuffer out = tdat.getChannel()
.map(FileChannel.MapMode.READ_WRITE, 0, length);
MappedByteBuffer out = tdat.getChannel().map(
FileChannel.MapMode.READ_WRITE, 0, length);
for(int i = 0; i < length; i++)
out.put((byte)'x');
System.out.println("Finished writing");

View File

@ -12,14 +12,15 @@ public class LockingMappedFiles {
static FileChannel fc;
public static void
main(String[] args) throws Exception {
fc =
new RandomAccessFile("test.dat", "rw").getChannel();
MappedByteBuffer out =
fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
fc = new RandomAccessFile("test.dat", "rw")
.getChannel();
MappedByteBuffer out = fc.map(
FileChannel.MapMode.READ_WRITE, 0, LENGTH);
for(int i = 0; i < LENGTH; i++)
out.put((byte)'x');
new LockAndModify(out, 0, 0 + LENGTH/3);
new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);
new LockAndModify(
out, LENGTH/2, LENGTH/2 + LENGTH/4);
}
private static class LockAndModify extends Thread {
private ByteBuffer buff;

144
newio/MappedIO.java Normal file
View File

@ -0,0 +1,144 @@
// newio/MappedIO.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class MappedIO {
private static int numOfInts = 4_000_000;
private static int numOfUbuffInts = 100_000;
private abstract static class Tester {
private String name;
public Tester(String name) {
this.name = name;
}
public void runTest() {
System.out.print(name + ": ");
long start = System.nanoTime();
test();
double duration = System.nanoTime() - start;
System.out.format("%.3f%n", duration/1.0e9);
}
public abstract void test();
}
private static Tester[] tests = {
new Tester("Stream Write") {
@Override
public void test() {
try(
DataOutputStream dos =
new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(
new File("temp.tmp"))))
) {
for(int i = 0; i < numOfInts; i++)
dos.writeInt(i);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
},
new Tester("Mapped Write") {
@Override
public void test() {
try(
FileChannel fc =
new RandomAccessFile("temp.tmp", "rw")
.getChannel()
) {
IntBuffer ib =
fc.map(FileChannel.MapMode.READ_WRITE,
0, fc.size()).asIntBuffer();
for(int i = 0; i < numOfInts; i++)
ib.put(i);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
},
new Tester("Stream Read") {
@Override
public void test() {
try(
DataInputStream dis =
new DataInputStream(
new BufferedInputStream(
new FileInputStream("temp.tmp")))
) {
for(int i = 0; i < numOfInts; i++)
dis.readInt();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
},
new Tester("Mapped Read") {
@Override
public void test() {
try(
FileChannel fc = new FileInputStream(
new File("temp.tmp")).getChannel()
) {
IntBuffer ib =
fc.map(FileChannel.MapMode.READ_ONLY,
0, fc.size()).asIntBuffer();
while(ib.hasRemaining())
ib.get();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
},
new Tester("Stream Read/Write") {
@Override
public void test() {
try(
RandomAccessFile raf =
new RandomAccessFile(
new File("temp.tmp"), "rw")
) {
raf.writeInt(1);
for(int i = 0; i < numOfUbuffInts; i++) {
raf.seek(raf.length() - 4);
raf.writeInt(raf.readInt());
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
},
new Tester("Mapped Read/Write") {
@Override
public void test() {
try(
FileChannel fc = new RandomAccessFile(
new File("temp.tmp"), "rw").getChannel()
) {
IntBuffer ib =
fc.map(FileChannel.MapMode.READ_WRITE,
0, fc.size()).asIntBuffer();
ib.put(0);
for(int i = 1; i < numOfUbuffInts; i++)
ib.put(ib.get(i - 1));
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
};
public static void main(String[] args) {
Arrays.stream(tests).forEach(Tester::runTest);
}
}
/* Output:
Stream Write: 0.269
Mapped Write: 0.022
Stream Read: 0.262
Mapped Read: 0.010
Stream Read/Write: 1.620
Mapped Read/Write: 0.007
*/

View File

@ -8,8 +8,7 @@ import java.nio.channels.*;
import java.io.*;
public class TransferTo {
public static void
main(String[] args) throws Exception {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println(
"arguments: sourcefile destfile");
@ -24,6 +23,8 @@ public class TransferTo {
in.transferTo(0, in.size(), out);
// Or:
// out.transferFrom(in, 0, in.size());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -17,7 +17,8 @@ public class UsingBuffers {
}
public static void main(String[] args) {
char[] data = "UsingBuffers".toCharArray();
ByteBuffer bb = ByteBuffer.allocate(data.length * 2);
ByteBuffer bb =
ByteBuffer.allocate(data.length * 2);
CharBuffer cb = bb.asCharBuffer();
cb.put(data);
System.out.println(cb.rewind());

View File

@ -11,26 +11,23 @@ public class OSExecute {
public static void command(String command) {
boolean err = false;
try {
Process process =
new ProcessBuilder(command.split(" ")).start();
Process process = new ProcessBuilder(
command.split(" ")).start();
try(
BufferedReader results = new BufferedReader(
new InputStreamReader(process.getInputStream()));
new InputStreamReader(
process.getInputStream()));
BufferedReader errors = new BufferedReader(
new InputStreamReader(
process.getErrorStream()))
) {
String s;
while((s = results.readLine())!= null)
System.out.println(s);
// Report errors and return nonzero value
// to calling process if there are problems:
while((s = errors.readLine())!= null) {
System.err.println(s);
err = true;
}
results.lines()
.forEach(System.out::println);
err = errors.lines()
.peek(System.err::println)
.count() > 0;
}
} catch(Exception e) {
} catch(IOException e) {
throw new RuntimeException(e);
}
if(err)

View File

@ -4,6 +4,9 @@
// Visit http://OnJava8.com for more book information.
package onjava;
public class OSExecuteException extends RuntimeException {
public OSExecuteException(String why) { super(why); }
public class
OSExecuteException extends RuntimeException {
public OSExecuteException(String why) {
super(why);
}
}

View File

@ -7,9 +7,17 @@ package onjava;
import java.util.concurrent.*;
public class TimedAbort {
private volatile boolean restart = true;
public TimedAbort(int n, String msg) {
CompletableFuture.runAsync(() -> {
new Nap(1000 * n);
try {
while(restart) {
restart = false;
TimeUnit.SECONDS.sleep(n);
}
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(msg);
System.exit(0);
});
@ -17,4 +25,5 @@ public class TimedAbort {
public TimedAbort(int n) {
this(n, "TimedAbort " + n);
}
public void restart() { restart = true; }
}

View File

@ -7,7 +7,8 @@ import java.io.*;
public class ChangeSystemOut {
public static void main(String[] args) {
PrintWriter out = new PrintWriter(System.out, true);
PrintWriter out =
new PrintWriter(System.out, true);
out.println("Hello, world");
}
}

View File

@ -7,15 +7,14 @@ import java.io.*;
import onjava.TimedAbort;
public class Echo {
public static void
main(String[] args) throws IOException {
new TimedAbort(4);
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s=stdin.readLine()) != null &&
s.length() != 0)
System.out.println(s);
// An empty line or Ctrl-Z terminates the program
public static void main(String[] args) {
TimedAbort abort = new TimedAbort(2);
new BufferedReader(
new InputStreamReader(System.in))
.lines()
.peek(ln -> abort.restart())
.forEach(System.out::println);
// Ctrl-Z or two seconds inactivity
// terminates the program
}
}

View File

@ -6,8 +6,7 @@
import java.io.*;
public class Redirecting {
public static void
main(String[] args) throws IOException {
public static void main(String[] args) {
PrintStream console = System.out;
try(
BufferedInputStream in = new BufferedInputStream(
@ -19,13 +18,14 @@ public class Redirecting {
System.setIn(in);
System.setOut(out);
System.setErr(out);
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = br.readLine()) != null)
System.out.println(s);
out.close(); // Remember this!
new BufferedReader(
new InputStreamReader(System.in))
.lines()
.forEach(System.out::println);
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
System.setOut(console);
}
System.setOut(console);
}
}