Update from latest version of book
This commit is contained in:
parent
a40b9896ba
commit
56ec933b8b
@ -4,7 +4,7 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// Creating non-embedded tests.
|
// Creating non-embedded tests.
|
||||||
package annotations;
|
package annotations;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitComposition {
|
public class AtUnitComposition {
|
||||||
@ -18,8 +18,7 @@ public class AtUnitComposition {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit " +
|
"java onjava.atunit.AtUnit AtUnitComposition.class");
|
||||||
" AtUnitComposition");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package annotations;
|
package annotations;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitExample1 {
|
public class AtUnitExample1 {
|
||||||
@ -24,7 +24,7 @@ public class AtUnitExample1 {
|
|||||||
@Test boolean anotherDisappointment() { return false; }
|
@Test boolean anotherDisappointment() { return false; }
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit AtUnitExample1");
|
"java onjava.atunit.AtUnit AtUnitExample1.class");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
// Assertions and exceptions can be used in @Tests.
|
// Assertions and exceptions can be used in @Tests.
|
||||||
package annotations;
|
package annotations;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitExample2 {
|
public class AtUnitExample2 {
|
||||||
@ -32,7 +32,7 @@ public class AtUnitExample2 {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit AtUnitExample2");
|
"java onjava.atunit.AtUnit AtUnitExample2.class");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package annotations;
|
package annotations;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitExample3 {
|
public class AtUnitExample3 {
|
||||||
@ -27,7 +27,7 @@ public class AtUnitExample3 {
|
|||||||
@Test boolean m2() { return methodTwo() == 2; }
|
@Test boolean m2() { return methodTwo() == 2; }
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit AtUnitExample3");
|
"java onjava.atunit.AtUnit AtUnitExample3.class");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package annotations;
|
package annotations;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitExample4 {
|
public class AtUnitExample4 {
|
||||||
@ -58,7 +58,7 @@ public class AtUnitExample4 {
|
|||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
System.out.println("starting");
|
System.out.println("starting");
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit AtUnitExample4");
|
"java onjava.atunit.AtUnit AtUnitExample4.class");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package annotations;
|
package annotations;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitExample5 {
|
public class AtUnitExample5 {
|
||||||
@ -42,7 +42,7 @@ public class AtUnitExample5 {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit AtUnitExample5");
|
"java onjava.atunit.AtUnit AtUnitExample5.class");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// Creating non-embedded tests.
|
// Creating non-embedded tests.
|
||||||
package annotations;
|
package annotations;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnitExternalTest extends AtUnitExample1 {
|
public class AtUnitExternalTest extends AtUnitExample1 {
|
||||||
@ -14,8 +14,7 @@ public class AtUnitExternalTest extends AtUnitExample1 {
|
|||||||
@Test boolean _methodTwo() { return methodTwo() == 2; }
|
@Test boolean _methodTwo() { return methodTwo() == 2; }
|
||||||
public static void main(String[] args) throws Exception{
|
public static void main(String[] args) throws Exception{
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit " +
|
"java onjava.atunit.AtUnit AtUnitExternalTest.class");
|
||||||
"AtUnitExternalTest");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package annotations;
|
package annotations;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class HashSetTest {
|
public class HashSetTest {
|
||||||
@ -23,7 +23,7 @@ public class HashSetTest {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit HashSetTest");
|
"java onjava.atunit.AtUnit HashSetTest.class");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -4,7 +4,7 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// Applying @Unit to generics.
|
// Applying @Unit to generics.
|
||||||
package annotations;
|
package annotations;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class StackLStringTest extends StackL<String> {
|
public class StackLStringTest extends StackL<String> {
|
||||||
@ -28,8 +28,7 @@ public class StackLStringTest extends StackL<String> {
|
|||||||
}
|
}
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
OSExecute.command(
|
OSExecute.command(
|
||||||
"java com.mindviewinc.atunit.AtUnit " +
|
"java onjava.atunit.AtUnit StackLStringTest.class");
|
||||||
"StackLStringTest");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package annotations;
|
package annotations;
|
||||||
import com.mindviewinc.atunit.*;
|
import onjava.atunit.*;
|
||||||
|
|
||||||
public class Testable {
|
public class Testable {
|
||||||
public void execute() {
|
public void execute() {
|
||||||
|
@ -7,8 +7,6 @@
|
|||||||
<import file="../Ant-Clean.xml"/>
|
<import file="../Ant-Clean.xml"/>
|
||||||
|
|
||||||
<target name="run" description="Compile and run" depends="build">
|
<target name="run" description="Compile and run" depends="build">
|
||||||
<jrun cls="com.mindviewinc.atunit.AtUnit" dirpath="../com/mindviewinc/atunit" />
|
|
||||||
<jrun cls="com.mindviewinc.atunit.ClassNameFinder" dirpath="../com/mindviewinc/atunit" />
|
|
||||||
</target>
|
</target>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -3,20 +3,25 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import onjava.*;
|
import java.nio.file.*;
|
||||||
|
|
||||||
public class UniqueWords {
|
public class UniqueWords {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) throws Exception {
|
||||||
Set<String> words = new TreeSet<>(
|
List<String> lines =
|
||||||
new TextFile("SetOperations.java", "\\W+"));
|
Files.readAllLines(Paths.get("SetOperations.java"));
|
||||||
|
Set<String> words = new TreeSet<>();
|
||||||
|
for(String line : lines)
|
||||||
|
for(String word : line.split("\\W+"))
|
||||||
|
if(word.trim().length() > 0)
|
||||||
|
words.add(word);
|
||||||
System.out.println(words);
|
System.out.println(words);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
[A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K, L,
|
[A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K, L,
|
||||||
M, N, Output, Print, Set, SetOperations, String, X, Y, Z,
|
M, N, Output, Set, SetOperations, String, System, X, Y, Z,
|
||||||
add, addAll, added, args, class, com, containers, contains,
|
add, addAll, added, args, class, containers, contains,
|
||||||
containsAll, false, from, import, in, java, main,
|
containsAll, false, from, import, in, java, main, new, out,
|
||||||
mindviewinc, new, print, public, remove, removeAll,
|
println, public, remove, removeAll, removed, set1, set2,
|
||||||
removed, set1, set2, split, static, to, true, util, void]
|
split, static, to, true, util, void]
|
||||||
*/
|
*/
|
||||||
|
@ -4,22 +4,26 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// Producing an alphabetic listing.
|
// Producing an alphabetic listing.
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import onjava.*;
|
import java.nio.file.*;
|
||||||
|
|
||||||
public class UniqueWordsAlphabetic {
|
public class UniqueWordsAlphabetic {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) throws Exception {
|
||||||
|
List<String> lines =
|
||||||
|
Files.readAllLines(Paths.get("SetOperations.java"));
|
||||||
Set<String> words =
|
Set<String> words =
|
||||||
new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
|
new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
|
||||||
words.addAll(
|
for(String line : lines)
|
||||||
new TextFile("SetOperations.java", "\\W+"));
|
for(String word : line.split("\\W+"))
|
||||||
|
if(word.trim().length() > 0)
|
||||||
|
words.add(word);
|
||||||
System.out.println(words);
|
System.out.println(words);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
[A, add, addAll, added, args, B, C, class, Collections,
|
[A, add, addAll, added, args, B, C, class, Collections,
|
||||||
com, containers, contains, containsAll, D, E, F, false,
|
containers, contains, containsAll, D, E, F, false, from, G,
|
||||||
from, G, H, HashSet, I, import, in, J, java, K, L, M, main,
|
H, HashSet, I, import, in, J, java, K, L, M, main, N, new,
|
||||||
mindviewinc, N, new, Output, Print, public, remove,
|
out, Output, println, public, remove, removeAll, removed,
|
||||||
removeAll, removed, Set, set1, set2, SetOperations, split,
|
Set, set1, set2, SetOperations, split, static, String,
|
||||||
static, String, to, true, util, void, X, Y, Z]
|
System, to, true, util, void, X, Y, Z]
|
||||||
*/
|
*/
|
||||||
|
@ -4,8 +4,10 @@
|
|||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// {Args: VendingMachineInput.txt}
|
// {Args: VendingMachineInput.txt}
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.function.*;
|
import java.util.function.*;
|
||||||
import onjava.*;
|
import java.nio.file.*;
|
||||||
|
import java.util.stream.*;
|
||||||
|
|
||||||
enum Category {
|
enum Category {
|
||||||
MONEY(Input.NICKEL, Input.DIME,
|
MONEY(Input.NICKEL, Input.DIME,
|
||||||
@ -130,8 +132,16 @@ class RandomInputSupplier implements Supplier<Input> {
|
|||||||
class FileInputSupplier implements Supplier<Input> {
|
class FileInputSupplier implements Supplier<Input> {
|
||||||
private Iterator<String> input;
|
private Iterator<String> input;
|
||||||
public FileInputSupplier(String fileName) {
|
public FileInputSupplier(String fileName) {
|
||||||
// Skip the comment line in the input file:
|
try {
|
||||||
input = new TextFile(fileName, ";").listIterator(1);
|
input = Files.lines(Paths.get(fileName))
|
||||||
|
.skip(1) // Skip the comment line
|
||||||
|
.flatMap(s -> Arrays.stream(s.split(";")))
|
||||||
|
.map(String::trim)
|
||||||
|
.collect(Collectors.toList())
|
||||||
|
.iterator();
|
||||||
|
} catch(IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@Override
|
@Override
|
||||||
public Input get() {
|
public Input get() {
|
||||||
@ -143,12 +153,12 @@ class FileInputSupplier implements Supplier<Input> {
|
|||||||
/* Output:
|
/* Output:
|
||||||
25
|
25
|
||||||
50
|
50
|
||||||
Insufficient money for CHIPS
|
75
|
||||||
50
|
here is your CHIPS
|
||||||
150
|
0
|
||||||
250
|
100
|
||||||
|
200
|
||||||
here is your TOOTHPASTE
|
here is your TOOTHPASTE
|
||||||
Your change: 50
|
|
||||||
0
|
0
|
||||||
25
|
25
|
||||||
35
|
35
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
import java.nio.file.*;
|
import java.nio.file.*;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
public class AddAndSubtractPaths {
|
public class AddAndSubtractPaths {
|
||||||
static Path base = Paths.get("..", "..", "..")
|
static Path base = Paths.get("..", "..", "..")
|
||||||
@ -14,6 +15,11 @@ public class AddAndSubtractPaths {
|
|||||||
base.relativize(result));
|
base.relativize(result));
|
||||||
else
|
else
|
||||||
System.out.println("(" + id + ") " + result);
|
System.out.println("(" + id + ") " + result);
|
||||||
|
try {
|
||||||
|
System.out.println("RealPath: " + result.toRealPath());
|
||||||
|
} catch (IOException e) {
|
||||||
|
System.out.println(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println(System.getProperty("os.name"));
|
System.out.println(System.getProperty("os.name"));
|
||||||
@ -41,6 +47,7 @@ public class AddAndSubtractPaths {
|
|||||||
Path p5 = Paths.get("").toAbsolutePath();
|
Path p5 = Paths.get("").toAbsolutePath();
|
||||||
show(9, p5);
|
show(9, p5);
|
||||||
show(10, p5.resolveSibling("strings"));
|
show(10, p5.resolveSibling("strings"));
|
||||||
|
show(11, Paths.get("nonexistent"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
@ -48,13 +55,32 @@ Windows 10
|
|||||||
C:\Users\Bruce\Documents\Git
|
C:\Users\Bruce\Documents\Git
|
||||||
(1)r on-
|
(1)r on-
|
||||||
java\ExtractedExamples\files\AddAndSubtractPaths.java
|
java\ExtractedExamples\files\AddAndSubtractPaths.java
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-
|
||||||
|
java\ExtractedExamples\files\AddAndSubtractPaths.java
|
||||||
(2)r on-java\ExtractedExamples\strings\..\files
|
(2)r on-java\ExtractedExamples\strings\..\files
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-
|
||||||
|
java\ExtractedExamples\files
|
||||||
(3)r on-java\ExtractedExamples\files
|
(3)r on-java\ExtractedExamples\files
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-
|
||||||
|
java\ExtractedExamples\files
|
||||||
(4) ..\..
|
(4) ..\..
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-java
|
||||||
(5) ..\..
|
(5) ..\..
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-java
|
||||||
(6)r on-java
|
(6)r on-java
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-java
|
||||||
(7)r on-java\ExtractedExamples\files\.\..\..
|
(7)r on-java\ExtractedExamples\files\.\..\..
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-java
|
||||||
(8)r on-java
|
(8)r on-java
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-java
|
||||||
(9)r on-java\ExtractedExamples\files
|
(9)r on-java\ExtractedExamples\files
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-
|
||||||
|
java\ExtractedExamples\files
|
||||||
(10)r on-java\ExtractedExamples\strings
|
(10)r on-java\ExtractedExamples\strings
|
||||||
|
RealPath: C:\Users\Bruce\Documents\Git\on-
|
||||||
|
java\ExtractedExamples\strings
|
||||||
|
(11) nonexistent
|
||||||
|
java.nio.file.NoSuchFileException:
|
||||||
|
C:\Users\Bruce\Documents\Git\on-
|
||||||
|
java\ExtractedExamples\files\nonexistent
|
||||||
*/
|
*/
|
||||||
|
@ -1,40 +0,0 @@
|
|||||||
// files/DirList.java
|
|
||||||
// ©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.
|
|
||||||
// Display a directory listing using regular expressions.
|
|
||||||
// {Args: "D.*\.java"}
|
|
||||||
import java.util.regex.*;
|
|
||||||
import java.io.*;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class DirList {
|
|
||||||
public static void main(String[] args) {
|
|
||||||
File path = new File(".");
|
|
||||||
String[] list;
|
|
||||||
if(args.length == 0)
|
|
||||||
list = path.list();
|
|
||||||
else
|
|
||||||
list = path.list(new DirFilter(args[0]));
|
|
||||||
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
|
|
||||||
for(String dirItem : list)
|
|
||||||
System.out.println(dirItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class DirFilter implements FilenameFilter {
|
|
||||||
private Pattern pattern;
|
|
||||||
public DirFilter(String regex) {
|
|
||||||
pattern = Pattern.compile(regex);
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public boolean accept(File dir, String name) {
|
|
||||||
return pattern.matcher(name).matches();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output:
|
|
||||||
DirectoryDemo.java
|
|
||||||
DirList.java
|
|
||||||
DirList2.java
|
|
||||||
DirList3.java
|
|
||||||
*/
|
|
@ -1,39 +0,0 @@
|
|||||||
// files/DirList2.java
|
|
||||||
// ©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 anonymous inner classes.
|
|
||||||
// {Args: "D.*\.java"}
|
|
||||||
import java.util.regex.*;
|
|
||||||
import java.io.*;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class DirList2 {
|
|
||||||
public static FilenameFilter filter(final String regex) {
|
|
||||||
// Creation of anonymous inner class:
|
|
||||||
return new FilenameFilter() {
|
|
||||||
private Pattern pattern = Pattern.compile(regex);
|
|
||||||
@Override
|
|
||||||
public boolean accept(File dir, String name) {
|
|
||||||
return pattern.matcher(name).matches();
|
|
||||||
}
|
|
||||||
}; // End of anonymous inner class
|
|
||||||
}
|
|
||||||
public static void main(String[] args) {
|
|
||||||
File path = new File(".");
|
|
||||||
String[] list;
|
|
||||||
if(args.length == 0)
|
|
||||||
list = path.list();
|
|
||||||
else
|
|
||||||
list = path.list(filter(args[0]));
|
|
||||||
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
|
|
||||||
for(String dirItem : list)
|
|
||||||
System.out.println(dirItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output:
|
|
||||||
DirectoryDemo.java
|
|
||||||
DirList.java
|
|
||||||
DirList2.java
|
|
||||||
DirList3.java
|
|
||||||
*/
|
|
@ -1,35 +0,0 @@
|
|||||||
// files/DirList3.java
|
|
||||||
// ©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.
|
|
||||||
// Building the anonymous inner class "in-place."
|
|
||||||
// {Args: "D.*\.java"}
|
|
||||||
import java.util.regex.*;
|
|
||||||
import java.io.*;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class DirList3 {
|
|
||||||
public static void main(final String[] args) {
|
|
||||||
File path = new File(".");
|
|
||||||
String[] list;
|
|
||||||
if(args.length == 0)
|
|
||||||
list = path.list();
|
|
||||||
else
|
|
||||||
list = path.list(new FilenameFilter() {
|
|
||||||
private Pattern pattern = Pattern.compile(args[0]);
|
|
||||||
@Override
|
|
||||||
public boolean accept(File dir, String name) {
|
|
||||||
return pattern.matcher(name).matches();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
|
|
||||||
for(String dirItem : list)
|
|
||||||
System.out.println(dirItem);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output:
|
|
||||||
DirectoryDemo.java
|
|
||||||
DirList.java
|
|
||||||
DirList2.java
|
|
||||||
DirList3.java
|
|
||||||
*/
|
|
94
files/Directories.java
Normal file
94
files/Directories.java
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
// files/Directories.java
|
||||||
|
// ©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.
|
||||||
|
import java.util.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import onjava.RmDir;
|
||||||
|
|
||||||
|
public class Directories {
|
||||||
|
static Path test = Paths.get("test");
|
||||||
|
static String sep =
|
||||||
|
FileSystems.getDefault().getSeparator();
|
||||||
|
static List<String> parts =
|
||||||
|
Arrays.asList("foo", "bar", "baz", "bingo");
|
||||||
|
static Path makeVariant() {
|
||||||
|
Collections.rotate(parts, 1);
|
||||||
|
return Paths.get("test", String.join(sep, parts));
|
||||||
|
}
|
||||||
|
static void refreshTestDir() throws Exception {
|
||||||
|
if(Files.exists(test))
|
||||||
|
RmDir.rmdir(test);
|
||||||
|
if(!Files.exists(test))
|
||||||
|
Files.createDirectory(test);
|
||||||
|
}
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
refreshTestDir();
|
||||||
|
Files.createFile(test.resolve("Hello.txt"));
|
||||||
|
Path variant = makeVariant();
|
||||||
|
// Throws exception (too many levels):
|
||||||
|
try {
|
||||||
|
Files.createDirectory(variant);
|
||||||
|
} catch(Exception e) {
|
||||||
|
System.out.println("Nope, that doesn't work.");
|
||||||
|
}
|
||||||
|
populateTestDir();
|
||||||
|
Path tempdir =
|
||||||
|
Files.createTempDirectory(test, "dirprefix");
|
||||||
|
Files.createTempFile(tempdir, "tpre", ".non");
|
||||||
|
Files.newDirectoryStream(test)
|
||||||
|
.forEach(System.out::println);
|
||||||
|
System.out.println("*********");
|
||||||
|
Files.walk(test).forEach(System.out::println);
|
||||||
|
}
|
||||||
|
static void populateTestDir() throws Exception {
|
||||||
|
for(int i = 0; i < parts.size(); i++) {
|
||||||
|
Path variant = makeVariant();
|
||||||
|
if(!Files.exists(variant)) {
|
||||||
|
Files.createDirectories(variant);
|
||||||
|
Files.copy(Paths.get("Directories.java"),
|
||||||
|
variant.resolve("File.txt"));
|
||||||
|
Files.createTempFile(variant, null, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
Nope, that doesn't work.
|
||||||
|
test\bar
|
||||||
|
test\baz
|
||||||
|
test\bingo
|
||||||
|
test\dirprefix7027855145419397204
|
||||||
|
test\foo
|
||||||
|
test\Hello.txt
|
||||||
|
*********
|
||||||
|
test
|
||||||
|
test\bar
|
||||||
|
test\bar\baz
|
||||||
|
test\bar\baz\bingo
|
||||||
|
test\bar\baz\bingo\foo
|
||||||
|
test\bar\baz\bingo\foo\1220228689745443997.tmp
|
||||||
|
test\bar\baz\bingo\foo\File.txt
|
||||||
|
test\baz
|
||||||
|
test\baz\bingo
|
||||||
|
test\baz\bingo\foo
|
||||||
|
test\baz\bingo\foo\bar
|
||||||
|
test\baz\bingo\foo\bar\5075758669780325498.tmp
|
||||||
|
test\baz\bingo\foo\bar\File.txt
|
||||||
|
test\bingo
|
||||||
|
test\bingo\foo
|
||||||
|
test\bingo\foo\bar
|
||||||
|
test\bingo\foo\bar\baz
|
||||||
|
test\bingo\foo\bar\baz\8539170686730128217.tmp
|
||||||
|
test\bingo\foo\bar\baz\File.txt
|
||||||
|
test\dirprefix7027855145419397204
|
||||||
|
test\dirprefix7027855145419397204\tpre8937492273233690134.n
|
||||||
|
on
|
||||||
|
test\foo
|
||||||
|
test\foo\bar
|
||||||
|
test\foo\bar\baz
|
||||||
|
test\foo\bar\baz\bingo
|
||||||
|
test\foo\bar\baz\bingo\4151379795190009123.tmp
|
||||||
|
test\foo\bar\baz\bingo\File.txt
|
||||||
|
test\Hello.txt
|
||||||
|
*/
|
@ -1,40 +0,0 @@
|
|||||||
// files/DirectoryDemo.java
|
|
||||||
// ©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.
|
|
||||||
// Sample use of Directory utilities.
|
|
||||||
import java.io.*;
|
|
||||||
import onjava.*;
|
|
||||||
|
|
||||||
public class DirectoryDemo {
|
|
||||||
public static void main(String[] args) {
|
|
||||||
// All directories:
|
|
||||||
PPrint.pprint(Directory.walk(".").dirs);
|
|
||||||
// All files beginning with 'T'
|
|
||||||
for(File file : Directory.local(".", "T.*"))
|
|
||||||
System.out.println(file);
|
|
||||||
System.out.println("----------------------");
|
|
||||||
// All Java files beginning with 'T':
|
|
||||||
for(File file : Directory.walk(".", "T.*\\.java"))
|
|
||||||
System.out.println(file);
|
|
||||||
System.out.println("======================");
|
|
||||||
// Class files containing "Z" or "z":
|
|
||||||
for(File file : Directory.walk(".",".*[Zz].*\\.class"))
|
|
||||||
System.out.println(file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output:
|
|
||||||
[.\xfiles]
|
|
||||||
.\TestEOF.class
|
|
||||||
.\TestEOF.java
|
|
||||||
.\TransferTo.class
|
|
||||||
.\TransferTo.java
|
|
||||||
----------------------
|
|
||||||
.\TestEOF.java
|
|
||||||
.\TransferTo.java
|
|
||||||
.\xfiles\ThawAlien.java
|
|
||||||
======================
|
|
||||||
.\FreezeAlien.class
|
|
||||||
.\GZIPcompress.class
|
|
||||||
.\ZipCompress.class
|
|
||||||
*/
|
|
58
files/Find.java
Normal file
58
files/Find.java
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
// files/Find.java
|
||||||
|
// ©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.
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
|
public class Find {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Path test = Paths.get("test");
|
||||||
|
Directories.refreshTestDir();
|
||||||
|
Directories.populateTestDir();
|
||||||
|
// Creating a *directory*, not a file:
|
||||||
|
Files.createDirectory(test.resolve("dir.tmp"));
|
||||||
|
|
||||||
|
PathMatcher matcher = FileSystems.getDefault()
|
||||||
|
.getPathMatcher("glob:**/*.{tmp,txt}");
|
||||||
|
Files.walk(test)
|
||||||
|
.filter(matcher::matches)
|
||||||
|
.forEach(System.out::println);
|
||||||
|
System.out.println("***************");
|
||||||
|
|
||||||
|
PathMatcher matcher2 = FileSystems.getDefault()
|
||||||
|
.getPathMatcher("glob:*.tmp");
|
||||||
|
Files.walk(test)
|
||||||
|
.map(Path::getFileName)
|
||||||
|
.filter(matcher2::matches)
|
||||||
|
.forEach(System.out::println);
|
||||||
|
System.out.println("***************");
|
||||||
|
|
||||||
|
Files.walk(test) // Only look for files
|
||||||
|
.filter(Files::isRegularFile)
|
||||||
|
.map(Path::getFileName)
|
||||||
|
.filter(matcher2::matches)
|
||||||
|
.forEach(System.out::println);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
test\bar\baz\bingo\foo\7502408684126514935.tmp
|
||||||
|
test\bar\baz\bingo\foo\File.txt
|
||||||
|
test\baz\bingo\foo\bar\5777895186852859683.tmp
|
||||||
|
test\baz\bingo\foo\bar\File.txt
|
||||||
|
test\bingo\foo\bar\baz\5734112745714386401.tmp
|
||||||
|
test\bingo\foo\bar\baz\File.txt
|
||||||
|
test\dir.tmp
|
||||||
|
test\foo\bar\baz\bingo\585102693362215677.tmp
|
||||||
|
test\foo\bar\baz\bingo\File.txt
|
||||||
|
***************
|
||||||
|
7502408684126514935.tmp
|
||||||
|
5777895186852859683.tmp
|
||||||
|
5734112745714386401.tmp
|
||||||
|
dir.tmp
|
||||||
|
585102693362215677.tmp
|
||||||
|
***************
|
||||||
|
7502408684126514935.tmp
|
||||||
|
5777895186852859683.tmp
|
||||||
|
5734112745714386401.tmp
|
||||||
|
585102693362215677.tmp
|
||||||
|
*/
|
27
files/ListOfLines.java
Normal file
27
files/ListOfLines.java
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
// files/ListOfLines.java
|
||||||
|
// ©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.
|
||||||
|
import java.util.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
|
public class ListOfLines {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
List<String> lines = Files.readAllLines(
|
||||||
|
Paths.get("../streams/Cheese.dat"));
|
||||||
|
for(String line : lines) {
|
||||||
|
if(line.startsWith("//"))
|
||||||
|
continue;
|
||||||
|
System.out.println(
|
||||||
|
line.substring(0, line.length()/2));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
Not much of a cheese
|
||||||
|
Finest in the
|
||||||
|
And what leads you
|
||||||
|
Well, it's
|
||||||
|
It's certainly uncon
|
||||||
|
*/
|
@ -1,86 +0,0 @@
|
|||||||
// files/MakeDirectories.java
|
|
||||||
// ©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.
|
|
||||||
// Demonstrates using the File class to
|
|
||||||
// create directories and manipulate files.
|
|
||||||
// {Args: MakeDirectoriesTest}
|
|
||||||
import java.io.*;
|
|
||||||
|
|
||||||
public class MakeDirectories {
|
|
||||||
private static void usage() {
|
|
||||||
System.err.println(
|
|
||||||
"Usage:MakeDirectories path1 ...\n" +
|
|
||||||
"Creates each path\n" +
|
|
||||||
"Usage:MakeDirectories -d path1 ...\n" +
|
|
||||||
"Deletes each path\n" +
|
|
||||||
"Usage:MakeDirectories -r path1 path2\n" +
|
|
||||||
"Renames from path1 to path2");
|
|
||||||
System.exit(1);
|
|
||||||
}
|
|
||||||
private static void fileData(File f) {
|
|
||||||
System.out.println(
|
|
||||||
"Absolute path: " + f.getAbsolutePath() +
|
|
||||||
"\n Can read: " + f.canRead() +
|
|
||||||
"\n Can write: " + f.canWrite() +
|
|
||||||
"\n getName: " + f.getName() +
|
|
||||||
"\n getParent: " + f.getParent() +
|
|
||||||
"\n getPath: " + f.getPath() +
|
|
||||||
"\n length: " + f.length() +
|
|
||||||
"\n lastModified: " + f.lastModified());
|
|
||||||
if(f.isFile())
|
|
||||||
System.out.println("It's a file");
|
|
||||||
else if(f.isDirectory())
|
|
||||||
System.out.println("It's a directory");
|
|
||||||
}
|
|
||||||
public static void main(String[] args) {
|
|
||||||
if(args.length < 1) usage();
|
|
||||||
if(args[0].equals("-r")) {
|
|
||||||
if(args.length != 3) usage();
|
|
||||||
File
|
|
||||||
old = new File(args[1]),
|
|
||||||
rname = new File(args[2]);
|
|
||||||
old.renameTo(rname);
|
|
||||||
fileData(old);
|
|
||||||
fileData(rname);
|
|
||||||
return; // Exit main
|
|
||||||
}
|
|
||||||
int count = 0;
|
|
||||||
boolean del = false;
|
|
||||||
if(args[0].equals("-d")) {
|
|
||||||
count++;
|
|
||||||
del = true;
|
|
||||||
}
|
|
||||||
count--;
|
|
||||||
while(++count < args.length) {
|
|
||||||
File f = new File(args[count]);
|
|
||||||
if(f.exists()) {
|
|
||||||
System.out.println(f + " exists");
|
|
||||||
if(del) {
|
|
||||||
System.out.println("deleting..." + f);
|
|
||||||
f.delete();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else { // Doesn't exist
|
|
||||||
if(!del) {
|
|
||||||
f.mkdirs();
|
|
||||||
System.out.println("created " + f);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fileData(f);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output:
|
|
||||||
created MakeDirectoriesTest
|
|
||||||
Absolute path: C:\Users\Bruce\Documents\GitHub\OnJava\Extra
|
|
||||||
ctedExamples\io\MakeDirectoriesTest
|
|
||||||
Can read: true
|
|
||||||
Can write: true
|
|
||||||
getName: MakeDirectoriesTest
|
|
||||||
getParent: null
|
|
||||||
getPath: MakeDirectoriesTest
|
|
||||||
length: 0
|
|
||||||
lastModified: 1442352598194
|
|
||||||
It's a directory
|
|
||||||
*/
|
|
57
files/PathWatcher.java
Normal file
57
files/PathWatcher.java
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
// files/PathWatcher.java
|
||||||
|
// ©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.
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import static java.nio.file.StandardWatchEventKinds.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
public class PathWatcher {
|
||||||
|
static Path test = Paths.get("test");
|
||||||
|
static void delTxtFiles() {
|
||||||
|
try {
|
||||||
|
Files.walk(test)
|
||||||
|
.filter(f ->
|
||||||
|
f.toString().endsWith(".txt"))
|
||||||
|
.forEach(f -> {
|
||||||
|
try {
|
||||||
|
System.out.println("deleting " + f);
|
||||||
|
Files.delete(f);
|
||||||
|
} catch(IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch(IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Directories.refreshTestDir();
|
||||||
|
Directories.populateTestDir();
|
||||||
|
Files.createFile(test.resolve("Hello.txt"));
|
||||||
|
WatchService watcher =
|
||||||
|
FileSystems.getDefault().newWatchService();
|
||||||
|
test.register(watcher, ENTRY_DELETE);
|
||||||
|
Executors.newSingleThreadScheduledExecutor().schedule(
|
||||||
|
PathWatcher::delTxtFiles,250,TimeUnit.MILLISECONDS);
|
||||||
|
WatchKey key = watcher.take();
|
||||||
|
for(WatchEvent evt : key.pollEvents()) {
|
||||||
|
System.out.println(
|
||||||
|
"evt.context(): " + evt.context() +
|
||||||
|
"\nevt.count(): " + evt.count() +
|
||||||
|
"\nevt.kind(): " + evt.kind());
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
deleting test\bar\baz\bingo\foo\File.txt
|
||||||
|
deleting test\baz\bingo\foo\bar\File.txt
|
||||||
|
deleting test\bingo\foo\bar\baz\File.txt
|
||||||
|
deleting test\foo\bar\baz\bingo\File.txt
|
||||||
|
deleting test\Hello.txt
|
||||||
|
evt.context(): Hello.txt
|
||||||
|
evt.count(): 1
|
||||||
|
evt.kind(): ENTRY_DELETE
|
||||||
|
*/
|
17
files/ReadLineStream.java
Normal file
17
files/ReadLineStream.java
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// files/ReadLineStream.java
|
||||||
|
// ©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.
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
|
public class ReadLineStream {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Files.lines(Paths.get("PathInfo.java"))
|
||||||
|
.skip(13)
|
||||||
|
.findFirst()
|
||||||
|
.ifPresent(System.out::println);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
show("RegularFile", Files.isRegularFile(p));
|
||||||
|
*/
|
22
files/StreamInAndOut.java
Normal file
22
files/StreamInAndOut.java
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
// files/StreamInAndOut.java
|
||||||
|
// ©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.
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
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", "UTF-8")) {
|
||||||
|
input
|
||||||
|
.map(String::toUpperCase)
|
||||||
|
.forEachOrdered(output::println);
|
||||||
|
} catch(Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
48
files/TreeWatcher.java
Normal file
48
files/TreeWatcher.java
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
// files/TreeWatcher.java
|
||||||
|
// ©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.
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import static java.nio.file.StandardWatchEventKinds.*;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
public class TreeWatcher {
|
||||||
|
static void watchDir(Path dir) {
|
||||||
|
try {
|
||||||
|
WatchService watcher =
|
||||||
|
FileSystems.getDefault().newWatchService();
|
||||||
|
dir.register(watcher, ENTRY_DELETE);
|
||||||
|
Executors.newSingleThreadExecutor().submit(() -> {
|
||||||
|
try {
|
||||||
|
WatchKey key = watcher.take();
|
||||||
|
for(WatchEvent evt : key.pollEvents()) {
|
||||||
|
System.out.println(
|
||||||
|
"evt.context(): " + evt.context() +
|
||||||
|
"\nevt.count(): " + evt.count() +
|
||||||
|
"\nevt.kind(): " + evt.kind());
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
} catch(InterruptedException e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch(IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Directories.refreshTestDir();
|
||||||
|
Directories.populateTestDir();
|
||||||
|
Files.walk(Paths.get("test"))
|
||||||
|
.filter(Files::isDirectory)
|
||||||
|
.forEach(TreeWatcher::watchDir);
|
||||||
|
PathWatcher.delTxtFiles();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
deleting test\bar\baz\bingo\foo\File.txt
|
||||||
|
evt.context(): File.txt
|
||||||
|
evt.count(): 1
|
||||||
|
evt.kind(): ENTRY_DELETE
|
||||||
|
*/
|
30
files/Writing.java
Normal file
30
files/Writing.java
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
// files/Writing.java
|
||||||
|
// ©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.
|
||||||
|
import java.util.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
|
public class Writing {
|
||||||
|
static Random rand = new Random(47);
|
||||||
|
static final int sz = 1000;
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
// Write bytes to a file:
|
||||||
|
byte[] bytes = new byte[sz];
|
||||||
|
rand.nextBytes(bytes);
|
||||||
|
Files.write(Paths.get("bytes.dat"), bytes);
|
||||||
|
System.out.println("bytes.dat: " +
|
||||||
|
Files.size(Paths.get("bytes.dat")));
|
||||||
|
|
||||||
|
// Write an iterable to a file:
|
||||||
|
List<String> lines = Files.readAllLines(
|
||||||
|
Paths.get("../streams/Cheese.dat"));
|
||||||
|
Files.write(Paths.get("Cheese.txt"), lines);
|
||||||
|
System.out.println("Cheese.txt: " +
|
||||||
|
Files.size(Paths.get("Cheese.txt")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
bytes.dat: 1000
|
||||||
|
Cheese.txt: 199
|
||||||
|
*/
|
@ -8,15 +8,18 @@
|
|||||||
|
|
||||||
<target name="run" description="Compile and run" depends="build">
|
<target name="run" description="Compile and run" depends="build">
|
||||||
<jrun cls="AddAndSubtractPaths" />
|
<jrun cls="AddAndSubtractPaths" />
|
||||||
<jrun cls="DirectoryDemo" />
|
<jrun cls="Directories" />
|
||||||
<jrun cls="DirList" arguments='"D.*\.java"' />
|
|
||||||
<jrun cls="DirList2" arguments='"D.*\.java"' />
|
|
||||||
<jrun cls="DirList3" arguments='"D.*\.java"' />
|
|
||||||
<jrun cls="File_System" />
|
<jrun cls="File_System" />
|
||||||
<jrun cls="MakeDirectories" arguments="MakeDirectoriesTest" />
|
<jrun cls="Find" />
|
||||||
|
<jrun cls="ListOfLines" />
|
||||||
<jrun cls="PartsOfPaths" />
|
<jrun cls="PartsOfPaths" />
|
||||||
<jrun cls="PathAnalysis" />
|
<jrun cls="PathAnalysis" />
|
||||||
<jrun cls="PathInfo" />
|
<jrun cls="PathInfo" />
|
||||||
|
<jrun cls="PathWatcher" />
|
||||||
|
<jrun cls="ReadLineStream" />
|
||||||
|
<jrun cls="StreamInAndOut" />
|
||||||
|
<jrun cls="TreeWatcher" />
|
||||||
|
<jrun cls="Writing" />
|
||||||
</target>
|
</target>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -1,22 +0,0 @@
|
|||||||
// onjava/BinaryFile.java
|
|
||||||
// ©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.
|
|
||||||
// Utility for reading files in binary form.
|
|
||||||
package onjava;
|
|
||||||
import java.io.*;
|
|
||||||
|
|
||||||
public class BinaryFile {
|
|
||||||
public static byte[] read(File bFile) throws IOException{
|
|
||||||
try(BufferedInputStream bf = new BufferedInputStream(
|
|
||||||
new FileInputStream(bFile))) {
|
|
||||||
byte[] data = new byte[bf.available()];
|
|
||||||
bf.read(data);
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public static byte[]
|
|
||||||
read(String bFile) throws IOException {
|
|
||||||
return read(new File(bFile).getAbsoluteFile());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,104 +0,0 @@
|
|||||||
// onjava/Directory.java
|
|
||||||
// ©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.
|
|
||||||
// Produce a sequence of File objects that match a
|
|
||||||
// regular expression in either a local directory,
|
|
||||||
// or by walking a directory tree.
|
|
||||||
package onjava;
|
|
||||||
import java.util.regex.*;
|
|
||||||
import java.io.*;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public final class Directory {
|
|
||||||
public static File[]
|
|
||||||
local(File dir, final String regex) {
|
|
||||||
return dir.listFiles(new FilenameFilter() {
|
|
||||||
private Pattern pattern = Pattern.compile(regex);
|
|
||||||
@Override
|
|
||||||
public boolean accept(File dir, String name) {
|
|
||||||
return pattern.matcher(
|
|
||||||
new File(name).getName()).matches();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
public static File[]
|
|
||||||
local(String path, final String regex) { // Overloaded
|
|
||||||
return local(new File(path), regex);
|
|
||||||
}
|
|
||||||
// A two-tuple for returning a pair of objects:
|
|
||||||
public static class TreeInfo implements Iterable<File> {
|
|
||||||
public List<File> files = new ArrayList<>();
|
|
||||||
public List<File> dirs = new ArrayList<>();
|
|
||||||
// The default iterable element is the file list:
|
|
||||||
@Override
|
|
||||||
public Iterator<File> iterator() {
|
|
||||||
return files.iterator();
|
|
||||||
}
|
|
||||||
void addAll(TreeInfo other) {
|
|
||||||
files.addAll(other.files);
|
|
||||||
dirs.addAll(other.dirs);
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return "dirs: " + PPrint.pformat(dirs) +
|
|
||||||
"\n\nfiles: " + PPrint.pformat(files);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
public static TreeInfo
|
|
||||||
walk(String start, String regex) { // Begin recursion
|
|
||||||
return recurseDirs(new File(start), regex);
|
|
||||||
}
|
|
||||||
public static TreeInfo
|
|
||||||
walk(File start, String regex) { // Overloaded
|
|
||||||
return recurseDirs(start, regex);
|
|
||||||
}
|
|
||||||
public static TreeInfo walk(File start) { // Everything
|
|
||||||
return recurseDirs(start, ".*");
|
|
||||||
}
|
|
||||||
public static TreeInfo walk(String start) {
|
|
||||||
return recurseDirs(new File(start), ".*");
|
|
||||||
}
|
|
||||||
static TreeInfo recurseDirs(File startDir, String regex){
|
|
||||||
TreeInfo result = new TreeInfo();
|
|
||||||
for(File item : startDir.listFiles()) {
|
|
||||||
if(item.isDirectory()) {
|
|
||||||
result.dirs.add(item);
|
|
||||||
result.addAll(recurseDirs(item, regex));
|
|
||||||
} else // Regular file
|
|
||||||
if(item.getName().matches(regex))
|
|
||||||
result.files.add(item);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
// Simple validation test:
|
|
||||||
public static void main(String[] args) {
|
|
||||||
if(args.length == 0)
|
|
||||||
System.out.println(walk("."));
|
|
||||||
else
|
|
||||||
for(String arg : args)
|
|
||||||
System.out.println(walk(arg));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output: (First 20 Lines)
|
|
||||||
dirs: []
|
|
||||||
files: [
|
|
||||||
.\BasicSupplier.class
|
|
||||||
.\BasicSupplier.java
|
|
||||||
.\BinaryFile.class
|
|
||||||
.\BinaryFile.java
|
|
||||||
.\CollectionData.class
|
|
||||||
.\CollectionData.java
|
|
||||||
.\ContainerMethodDifferences-erroroutput.txt
|
|
||||||
.\ContainerMethodDifferences-output.txt
|
|
||||||
.\ContainerMethodDifferences.class
|
|
||||||
.\ContainerMethodDifferences.java
|
|
||||||
.\ConvertTo.class
|
|
||||||
.\ConvertTo.java
|
|
||||||
.\CountingSupplier$Boolean.class
|
|
||||||
.\CountingSupplier$Byte.class
|
|
||||||
.\CountingSupplier$Character.class
|
|
||||||
.\CountingSupplier$Double.class
|
|
||||||
.\CountingSupplier$Float.class
|
|
||||||
...
|
|
||||||
*/
|
|
@ -1,29 +0,0 @@
|
|||||||
// onjava/PPrint.java
|
|
||||||
// ©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.
|
|
||||||
// Pretty-printer for collections
|
|
||||||
package onjava;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class PPrint {
|
|
||||||
public static String pformat(Collection<?> c) {
|
|
||||||
if(c.isEmpty()) return "[]";
|
|
||||||
StringBuilder result = new StringBuilder("[");
|
|
||||||
for(Object elem : c) {
|
|
||||||
if(c.size() != 1)
|
|
||||||
result.append("\n ");
|
|
||||||
result.append(elem);
|
|
||||||
}
|
|
||||||
if(c.size() != 1)
|
|
||||||
result.append("\n");
|
|
||||||
result.append("]");
|
|
||||||
return result.toString();
|
|
||||||
}
|
|
||||||
public static void pprint(Collection<?> c) {
|
|
||||||
System.out.println(pformat(c));
|
|
||||||
}
|
|
||||||
public static void pprint(Object[] c) {
|
|
||||||
System.out.println(pformat(Arrays.asList(c)));
|
|
||||||
}
|
|
||||||
}
|
|
@ -5,6 +5,7 @@
|
|||||||
// {ValidateByHand}
|
// {ValidateByHand}
|
||||||
package onjava;
|
package onjava;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
|
||||||
public class ProcessFiles {
|
public class ProcessFiles {
|
||||||
public interface Strategy {
|
public interface Strategy {
|
||||||
@ -39,9 +40,11 @@ public class ProcessFiles {
|
|||||||
}
|
}
|
||||||
public void
|
public void
|
||||||
processDirectoryTree(File root) throws IOException {
|
processDirectoryTree(File root) throws IOException {
|
||||||
for(File file : Directory.walk(
|
PathMatcher matcher = FileSystems.getDefault()
|
||||||
root.getAbsolutePath(), ".*\\." + ext))
|
.getPathMatcher("glob:**/*.{" + ext + "}");
|
||||||
strategy.process(file.getCanonicalFile());
|
Files.walk(root.toPath())
|
||||||
|
.filter(matcher::matches)
|
||||||
|
.forEach(p -> strategy.process(p.toFile()));
|
||||||
}
|
}
|
||||||
// Demonstration of how to use it:
|
// Demonstration of how to use it:
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
29
onjava/RmDir.java
Normal file
29
onjava/RmDir.java
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
// onjava/RmDir.java
|
||||||
|
// ©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 onjava;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.nio.file.attribute.BasicFileAttributes;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class RmDir {
|
||||||
|
public static void rmdir(Path dir) throws IOException {
|
||||||
|
Files.walkFileTree(dir, new SimpleFileVisitor<Path>(){
|
||||||
|
@Override
|
||||||
|
public FileVisitResult
|
||||||
|
visitFile(Path file, BasicFileAttributes attrs)
|
||||||
|
throws IOException {
|
||||||
|
Files.delete(file);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
@Override
|
||||||
|
public FileVisitResult
|
||||||
|
postVisitDirectory(Path dir, IOException exc)
|
||||||
|
throws IOException {
|
||||||
|
Files.delete(dir);
|
||||||
|
return FileVisitResult.CONTINUE;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -1,82 +0,0 @@
|
|||||||
// onjava/TextFile.java
|
|
||||||
// ©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.
|
|
||||||
// Static functions for reading and writing text files as
|
|
||||||
// a single String, and treating a file as an ArrayList.
|
|
||||||
package onjava;
|
|
||||||
import java.io.*;
|
|
||||||
import java.util.*;
|
|
||||||
|
|
||||||
public class TextFile extends ArrayList<String> {
|
|
||||||
// Read a file as a single String:
|
|
||||||
public static String read(String fileName) {
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
try {
|
|
||||||
try(BufferedReader in =
|
|
||||||
new BufferedReader(new FileReader(
|
|
||||||
new File(fileName).getAbsoluteFile()))) {
|
|
||||||
String s;
|
|
||||||
while((s = in.readLine()) != null) {
|
|
||||||
sb.append(s);
|
|
||||||
sb.append("\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch(IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
return sb.toString();
|
|
||||||
}
|
|
||||||
// Write a single file in one method call:
|
|
||||||
public static void write(String fileName, String text) {
|
|
||||||
try {
|
|
||||||
try(PrintWriter out = new PrintWriter(
|
|
||||||
new File(fileName).getAbsoluteFile())) {
|
|
||||||
out.print(text);
|
|
||||||
}
|
|
||||||
} catch(IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Read a file, split by any regular expression:
|
|
||||||
public TextFile(String fileName, String splitter) {
|
|
||||||
super(Arrays.asList(read(fileName).split(splitter)));
|
|
||||||
// Regular expression split() often leaves an empty
|
|
||||||
// String at the first position:
|
|
||||||
if(get(0).equals("")) remove(0);
|
|
||||||
}
|
|
||||||
// Normally read by lines:
|
|
||||||
public TextFile(String fileName) {
|
|
||||||
this(fileName, "\n");
|
|
||||||
}
|
|
||||||
public void write(String fileName) {
|
|
||||||
try {
|
|
||||||
try(PrintWriter out = new PrintWriter(
|
|
||||||
new File(fileName).getAbsoluteFile())) {
|
|
||||||
for(String item : this)
|
|
||||||
out.println(item);
|
|
||||||
}
|
|
||||||
} catch(IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Simple test:
|
|
||||||
public static void main(String[] args) {
|
|
||||||
String file = read("TextFile.java");
|
|
||||||
write("test.txt", file);
|
|
||||||
TextFile text = new TextFile("test.txt");
|
|
||||||
text.write("test2.txt");
|
|
||||||
// Break into unique sorted list of words:
|
|
||||||
TreeSet<String> words = new TreeSet<>(
|
|
||||||
new TextFile("TextFile.java", "\\W+"));
|
|
||||||
// Display the capitalized words:
|
|
||||||
System.out.println(words.headSet("a"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/* Output:
|
|
||||||
[0, ArrayList, Arrays, Break, BufferedReader,
|
|
||||||
BufferedWriter, Clean, Display, File, FileReader,
|
|
||||||
FileWriter, IOException, Normally, Output, PrintWriter,
|
|
||||||
Read, Regular, RuntimeException, Simple, Static, String,
|
|
||||||
StringBuilder, System, TextFile, Tools, TreeSet, W, Write]
|
|
||||||
*/
|
|
@ -1,12 +1,14 @@
|
|||||||
// com/mindviewinc/atunit/AtUnit.java
|
// onjava/atunit/AtUnit.java
|
||||||
// ©2016 MindView LLC: see Copyright.txt
|
// ©2016 MindView LLC: see Copyright.txt
|
||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// An annotation-based unit-test framework.
|
// An annotation-based unit-test framework.
|
||||||
package com.mindviewinc.atunit;
|
package onjava.atunit;
|
||||||
import java.lang.reflect.*;
|
import java.lang.reflect.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.stream.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
public class AtUnit implements ProcessFiles.Strategy {
|
public class AtUnit implements ProcessFiles.Strategy {
|
||||||
@ -32,7 +34,10 @@ public class AtUnit implements ProcessFiles.Strategy {
|
|||||||
public void process(File cFile) {
|
public void process(File cFile) {
|
||||||
try {
|
try {
|
||||||
String cName = ClassNameFinder.thisClass(
|
String cName = ClassNameFinder.thisClass(
|
||||||
BinaryFile.read(cFile));
|
Files.readAllBytes(cFile.toPath()));
|
||||||
|
if(!cName.startsWith("public:"))
|
||||||
|
return;
|
||||||
|
cName = cName.split(":")[1];
|
||||||
if(!cName.contains("."))
|
if(!cName.contains("."))
|
||||||
return; // Ignore unpackaged classes
|
return; // Ignore unpackaged classes
|
||||||
testClass = Class.forName(cName);
|
testClass = Class.forName(cName);
|
||||||
@ -95,7 +100,8 @@ public class AtUnit implements ProcessFiles.Strategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
static class TestMethods extends ArrayList<Method> {
|
public static
|
||||||
|
class TestMethods extends ArrayList<Method> {
|
||||||
void addIfTestMethod(Method m) {
|
void addIfTestMethod(Method m) {
|
||||||
if(m.getAnnotation(Test.class) == null)
|
if(m.getAnnotation(Test.class) == null)
|
||||||
return;
|
return;
|
||||||
@ -158,6 +164,3 @@ public class AtUnit implements ProcessFiles.Strategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
|
||||||
OK (0 tests)
|
|
||||||
*/
|
|
@ -1,9 +1,10 @@
|
|||||||
// com/mindviewinc/atunit/ClassNameFinder.java
|
// onjava/atunit/ClassNameFinder.java
|
||||||
// ©2016 MindView LLC: see Copyright.txt
|
// ©2016 MindView LLC: see Copyright.txt
|
||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
package com.mindviewinc.atunit;
|
package onjava.atunit;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
|
import java.nio.file.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import onjava.*;
|
import onjava.*;
|
||||||
|
|
||||||
@ -21,7 +22,7 @@ public class ClassNameFinder {
|
|||||||
int[] constant_pool = new int[constant_pool_count];
|
int[] constant_pool = new int[constant_pool_count];
|
||||||
for(int i = 1; i < constant_pool_count; i++) {
|
for(int i = 1; i < constant_pool_count; i++) {
|
||||||
int tag = data.read();
|
int tag = data.read();
|
||||||
int tableSize;
|
// int tableSize;
|
||||||
switch(tag) {
|
switch(tag) {
|
||||||
case 1: // UTF
|
case 1: // UTF
|
||||||
int length = data.readShort();
|
int length = data.readShort();
|
||||||
@ -49,16 +50,26 @@ public class ClassNameFinder {
|
|||||||
case 10: // METHOD_REF
|
case 10: // METHOD_REF
|
||||||
case 11: // INTERFACE_METHOD_REF
|
case 11: // INTERFACE_METHOD_REF
|
||||||
case 12: // NAME_AND_TYPE
|
case 12: // NAME_AND_TYPE
|
||||||
|
case 18: // Invoke Dynamic
|
||||||
data.readInt(); // discard 4 bytes;
|
data.readInt(); // discard 4 bytes;
|
||||||
break;
|
break;
|
||||||
|
case 15: // Method Handle
|
||||||
|
data.readByte();
|
||||||
|
data.readShort();
|
||||||
|
break;
|
||||||
|
case 16: // Method Type
|
||||||
|
data.readShort();
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
throw new RuntimeException("Bad tag " + tag);
|
throw new RuntimeException("Bad tag " + tag);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
short access_flags = data.readShort();
|
short access_flags = data.readShort();
|
||||||
|
String access = (access_flags & 0x0001) == 0 ?
|
||||||
|
"nonpublic:" : "public:";
|
||||||
int this_class = data.readShort();
|
int this_class = data.readShort();
|
||||||
int super_class = data.readShort();
|
int super_class = data.readShort();
|
||||||
return classNameTable.get(
|
return access + classNameTable.get(
|
||||||
offsetTable.get(this_class)).replace('/', '.');
|
offsetTable.get(this_class)).replace('/', '.');
|
||||||
} catch(IOException | RuntimeException e) {
|
} catch(IOException | RuntimeException e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
@ -66,23 +77,33 @@ public class ClassNameFinder {
|
|||||||
}
|
}
|
||||||
// Demonstration:
|
// Demonstration:
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
if(args.length > 0) {
|
PathMatcher matcher = FileSystems.getDefault()
|
||||||
for(String arg : args)
|
.getPathMatcher("glob:**/*.class");
|
||||||
System.out.println(
|
// Walk the entire tree:
|
||||||
thisClass(BinaryFile.read(new File(arg))));
|
Files.walk(Paths.get("."))
|
||||||
} else
|
.filter(matcher::matches)
|
||||||
// Walk the entire tree: <* Use NIO2 here *>
|
//.peek(System.out::println)
|
||||||
for(File klass : Directory.walk(".", ".*\\.class"))
|
.map(p -> {
|
||||||
System.out.println(
|
try {
|
||||||
thisClass(BinaryFile.read(klass)));
|
return thisClass(Files.readAllBytes(p));
|
||||||
|
} catch(Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(s -> s.startsWith("public:"))
|
||||||
|
// .filter(s -> s.indexOf('$') >= 0)
|
||||||
|
.map(s -> s.split(":")[1])
|
||||||
|
.filter(s -> !s.startsWith("enums."))
|
||||||
|
.filter(s -> s.contains("."))
|
||||||
|
.forEach(System.out::println);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
com.mindviewinc.atunit.AtUnit$TestMethods
|
onjava.atunit.AtUnit$TestMethods
|
||||||
com.mindviewinc.atunit.AtUnit
|
onjava.atunit.AtUnit
|
||||||
com.mindviewinc.atunit.ClassNameFinder
|
onjava.atunit.ClassNameFinder
|
||||||
com.mindviewinc.atunit.Test
|
onjava.atunit.Test
|
||||||
com.mindviewinc.atunit.TestObjectCleanup
|
onjava.atunit.TestObjectCleanup
|
||||||
com.mindviewinc.atunit.TestObjectCreate
|
onjava.atunit.TestObjectCreate
|
||||||
com.mindviewinc.atunit.TestProperty
|
onjava.atunit.TestProperty
|
||||||
*/
|
*/
|
@ -1,9 +1,9 @@
|
|||||||
// com/mindviewinc/atunit/Test.java
|
// onjava/atunit/Test.java
|
||||||
// ©2016 MindView LLC: see Copyright.txt
|
// ©2016 MindView LLC: see Copyright.txt
|
||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// The @Test tag.
|
// The @Test tag.
|
||||||
package com.mindviewinc.atunit;
|
package onjava.atunit;
|
||||||
import java.lang.annotation.*;
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
@Target(ElementType.METHOD)
|
@Target(ElementType.METHOD)
|
@ -1,9 +1,9 @@
|
|||||||
// com/mindviewinc/atunit/TestObjectCleanup.java
|
// onjava/atunit/TestObjectCleanup.java
|
||||||
// ©2016 MindView LLC: see Copyright.txt
|
// ©2016 MindView LLC: see Copyright.txt
|
||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// The @Unit @TestObjectCleanup tag.
|
// The @Unit @TestObjectCleanup tag.
|
||||||
package com.mindviewinc.atunit;
|
package onjava.atunit;
|
||||||
import java.lang.annotation.*;
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
@Target(ElementType.METHOD)
|
@Target(ElementType.METHOD)
|
@ -1,9 +1,9 @@
|
|||||||
// com/mindviewinc/atunit/TestObjectCreate.java
|
// onjava/atunit/TestObjectCreate.java
|
||||||
// ©2016 MindView LLC: see Copyright.txt
|
// ©2016 MindView LLC: see Copyright.txt
|
||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// The @Unit @TestObjectCreate tag.
|
// The @Unit @TestObjectCreate tag.
|
||||||
package com.mindviewinc.atunit;
|
package onjava.atunit;
|
||||||
import java.lang.annotation.*;
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
@Target(ElementType.METHOD)
|
@Target(ElementType.METHOD)
|
@ -1,9 +1,9 @@
|
|||||||
// com/mindviewinc/atunit/TestProperty.java
|
// onjava/atunit/TestProperty.java
|
||||||
// ©2016 MindView LLC: see Copyright.txt
|
// ©2016 MindView LLC: see Copyright.txt
|
||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// The @Unit @TestProperty tag.
|
// The @Unit @TestProperty tag.
|
||||||
package com.mindviewinc.atunit;
|
package onjava.atunit;
|
||||||
import java.lang.annotation.*;
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
// Both fields and methods can be tagged as properties:
|
// Both fields and methods can be tagged as properties:
|
@ -11,9 +11,9 @@
|
|||||||
<jrun cls="onjava.CountingIntegerList" dirpath="../onjava" />
|
<jrun cls="onjava.CountingIntegerList" dirpath="../onjava" />
|
||||||
<jrun cls="onjava.CountingMapData" dirpath="../onjava" />
|
<jrun cls="onjava.CountingMapData" dirpath="../onjava" />
|
||||||
<jrun cls="onjava.Countries" dirpath="../onjava" />
|
<jrun cls="onjava.Countries" dirpath="../onjava" />
|
||||||
<jrun cls="onjava.Directory" dirpath="../onjava" />
|
|
||||||
<jrun cls="onjava.Hex" dirpath="../onjava" />
|
<jrun cls="onjava.Hex" dirpath="../onjava" />
|
||||||
<jrun cls="onjava.TextFile" dirpath="../onjava" />
|
<jrun cls="onjava.atunit.AtUnit" dirpath="../onjava/atunit" />
|
||||||
|
<jrun cls="onjava.atunit.ClassNameFinder" dirpath="../onjava/atunit" />
|
||||||
</target>
|
</target>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
22
operators/Underscores.java
Normal file
22
operators/Underscores.java
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
// operators/Underscores.java
|
||||||
|
// ©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.
|
||||||
|
|
||||||
|
public class Underscores {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
double d = 341_435_936.445_667;
|
||||||
|
System.out.println(d);
|
||||||
|
int bin = 0b0010_1111_1010_1111_1010_1111_1010_1111;
|
||||||
|
System.out.println(Integer.toBinaryString(bin));
|
||||||
|
System.out.printf("%x\n", bin);
|
||||||
|
long hex = 0x7f_e9_b7_aa;
|
||||||
|
System.out.printf("%x\n", hex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
3.41435936445667E8
|
||||||
|
101111101011111010111110101111
|
||||||
|
2fafafaf
|
||||||
|
7fe9b7aa
|
||||||
|
*/
|
@ -26,6 +26,7 @@
|
|||||||
<jrun cls="ShortCircuit" />
|
<jrun cls="ShortCircuit" />
|
||||||
<jrun cls="StringOperators" />
|
<jrun cls="StringOperators" />
|
||||||
<jrun cls="TernaryIfElse" />
|
<jrun cls="TernaryIfElse" />
|
||||||
|
<jrun cls="Underscores" />
|
||||||
<jrun cls="URShift" />
|
<jrun cls="URShift" />
|
||||||
</target>
|
</target>
|
||||||
|
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
// Demonstrates the "transient" keyword.
|
// Demonstrates the "transient" keyword.
|
||||||
|
// {IgnoreReturnValue}
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
@ -12,7 +12,7 @@
|
|||||||
<jrun cls="Blip3" />
|
<jrun cls="Blip3" />
|
||||||
<jrun cls="Blips" />
|
<jrun cls="Blips" />
|
||||||
<jrun cls="FreezeAlien" />
|
<jrun cls="FreezeAlien" />
|
||||||
<jrun cls="Logon" />
|
<jrun cls="Logon" failOnError='false' />
|
||||||
<jrun cls="MyWorld" />
|
<jrun cls="MyWorld" />
|
||||||
<jrun cls="People" />
|
<jrun cls="People" />
|
||||||
<jrun cls="RecoverCADState" />
|
<jrun cls="RecoverCADState" />
|
||||||
|
@ -12,6 +12,6 @@ public class FileToWords {
|
|||||||
return Files.lines(Paths.get(filePath))
|
return Files.lines(Paths.get(filePath))
|
||||||
.skip(1) // First (comment) line
|
.skip(1) // First (comment) line
|
||||||
.flatMap(line ->
|
.flatMap(line ->
|
||||||
Pattern.compile("[ .,?]+").splitAsStream(line));
|
Pattern.compile("\\W+").splitAsStream(line));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
29
streams/TreeSetOfWords.java
Normal file
29
streams/TreeSetOfWords.java
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
// streams/TreeSetOfWords.java
|
||||||
|
// ©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.
|
||||||
|
import java.util.*;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.stream.*;
|
||||||
|
|
||||||
|
public class TreeSetOfWords {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Set<String> words2 =
|
||||||
|
Files.lines(Paths.get("TreeSetOfWords.java"))
|
||||||
|
.flatMap(s -> Arrays.stream(s.split("\\W+")))
|
||||||
|
.filter(s -> !s.matches("\\d+")) // No numbers
|
||||||
|
.map(String::trim)
|
||||||
|
.filter(s -> s.length() > 2)
|
||||||
|
.limit(100)
|
||||||
|
.collect(Collectors.toCollection(TreeSet::new));
|
||||||
|
System.out.println(words2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* Output:
|
||||||
|
[Arrays, Collectors, Exception, Files, Output, Paths, Set,
|
||||||
|
String, System, TreeSet, TreeSetOfWords, args, class,
|
||||||
|
collect, file, filter, flatMap, get, import, java, length,
|
||||||
|
limit, lines, main, map, matches, new, nio, numbers, out,
|
||||||
|
println, public, split, static, stream, streams, throws,
|
||||||
|
toCollection, trim, util, void, words2]
|
||||||
|
*/
|
@ -50,6 +50,7 @@
|
|||||||
<jrun cls="StreamOfOptionals" />
|
<jrun cls="StreamOfOptionals" />
|
||||||
<jrun cls="StreamOfRandoms" />
|
<jrun cls="StreamOfRandoms" />
|
||||||
<jrun cls="StreamOfStreams" />
|
<jrun cls="StreamOfStreams" />
|
||||||
|
<jrun cls="TreeSetOfWords" />
|
||||||
</target>
|
</target>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
@ -5,7 +5,8 @@
|
|||||||
// A very simple version of the "grep" program.
|
// A very simple version of the "grep" program.
|
||||||
// {Args: JGrep.java 'void|int|String'}
|
// {Args: JGrep.java 'void|int|String'}
|
||||||
import java.util.regex.*;
|
import java.util.regex.*;
|
||||||
import onjava.*;
|
import java.nio.file.*;
|
||||||
|
import java.util.stream.*;
|
||||||
|
|
||||||
public class JGrep {
|
public class JGrep {
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
@ -17,7 +18,8 @@ public class JGrep {
|
|||||||
// Iterate through the lines of the input file:
|
// Iterate through the lines of the input file:
|
||||||
int index = 0;
|
int index = 0;
|
||||||
Matcher m = p.matcher("");
|
Matcher m = p.matcher("");
|
||||||
for(String line : new TextFile(args[0])) {
|
for(String line :
|
||||||
|
Files.readAllLines(Paths.get(args[0]))) {
|
||||||
m.reset(line);
|
m.reset(line);
|
||||||
while(m.find())
|
while(m.find())
|
||||||
System.out.println(index++ + ": " +
|
System.out.println(index++ + ": " +
|
||||||
@ -26,28 +28,14 @@ public class JGrep {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* Output:
|
/* Output:
|
||||||
0: 'void: 21
|
Here's a block of text to use as input to
|
||||||
1: int: 27
|
the regular expression matcher. Note that we
|
||||||
2: String': 31
|
first extract the block of text by looking for
|
||||||
3: int: 19
|
the special delimiters, then process the
|
||||||
4: int: 4
|
extracted block.
|
||||||
5: int: 21
|
H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO
|
||||||
6: 'void: 3
|
thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE
|
||||||
7: int: 3
|
fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr
|
||||||
8: String': 3
|
thE spEcIAl dElImItErs, thEn prOcEss thE
|
||||||
9: int: 3
|
ExtrActEd blOck.
|
||||||
10: int: 3
|
|
||||||
11: int: 3
|
|
||||||
12: 'void: 3
|
|
||||||
13: int: 3
|
|
||||||
14: String': 3
|
|
||||||
15: int: 3
|
|
||||||
16: int: 4
|
|
||||||
17: int: 4
|
|
||||||
18: 'void: 4
|
|
||||||
19: int: 4
|
|
||||||
20: String': 4
|
|
||||||
21: int: 4
|
|
||||||
22: int: 4
|
|
||||||
23: int: 4
|
|
||||||
*/
|
*/
|
||||||
|
@ -3,7 +3,8 @@
|
|||||||
// We make no guarantees that this code is fit for any purpose.
|
// We make no guarantees that this code is fit for any purpose.
|
||||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||||
import java.util.regex.*;
|
import java.util.regex.*;
|
||||||
import onjava.*;
|
import java.nio.file.*;
|
||||||
|
import java.util.stream.*;
|
||||||
|
|
||||||
/*! Here's a block of text to use as input to
|
/*! Here's a block of text to use as input to
|
||||||
the regular expression matcher. Note that we
|
the regular expression matcher. Note that we
|
||||||
@ -13,11 +14,12 @@ import onjava.*;
|
|||||||
|
|
||||||
public class TheReplacements {
|
public class TheReplacements {
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
String s = TextFile.read("TheReplacements.java");
|
String s = Files.lines(
|
||||||
|
Paths.get("TheReplacements.java"))
|
||||||
|
.collect(Collectors.joining("\n"));
|
||||||
// Match the specially commented block of text above:
|
// Match the specially commented block of text above:
|
||||||
Matcher mInput =
|
Matcher mInput = Pattern.compile(
|
||||||
Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL)
|
"/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
|
||||||
.matcher(s);
|
|
||||||
if(mInput.find())
|
if(mInput.find())
|
||||||
s = mInput.group(1); // Captured by parentheses
|
s = mInput.group(1); // Captured by parentheses
|
||||||
// Replace two or more spaces with a single space:
|
// Replace two or more spaces with a single space:
|
||||||
|
@ -7,7 +7,9 @@ import swt.util.*;
|
|||||||
import org.eclipse.swt.*;
|
import org.eclipse.swt.*;
|
||||||
import org.eclipse.swt.widgets.*;
|
import org.eclipse.swt.widgets.*;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import onjava.*;
|
import java.io.IOException;
|
||||||
|
import java.nio.file.*;
|
||||||
|
import java.util.stream.*;
|
||||||
|
|
||||||
public class Menus implements SWTApplication {
|
public class Menus implements SWTApplication {
|
||||||
private static Shell shell;
|
private static Shell shell;
|
||||||
@ -16,11 +18,17 @@ public class Menus implements SWTApplication {
|
|||||||
shell = parent.getShell();
|
shell = parent.getShell();
|
||||||
Menu bar = new Menu(shell, SWT.BAR);
|
Menu bar = new Menu(shell, SWT.BAR);
|
||||||
shell.setMenuBar(bar);
|
shell.setMenuBar(bar);
|
||||||
Set<String> words = new TreeSet<>(
|
Set<String> words = null;
|
||||||
new TextFile("Menus.java", "\\W+"));
|
try {
|
||||||
|
words = Files.lines(Paths.get("Menus.java"))
|
||||||
|
.flatMap(s -> Arrays.stream(s.split("\\W+")))
|
||||||
|
.filter(s -> !s.matches("[0-9]+")) // No numbers
|
||||||
|
.map(String::trim)
|
||||||
|
.collect(Collectors.toCollection(TreeSet::new));
|
||||||
|
} catch(IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
Iterator<String> it = words.iterator();
|
Iterator<String> it = words.iterator();
|
||||||
while(it.next().matches("[0-9]+"))
|
|
||||||
; // Move past the numbers.
|
|
||||||
MenuItem[] mItem = new MenuItem[7];
|
MenuItem[] mItem = new MenuItem[7];
|
||||||
for(int i = 0; i < mItem.length; i++) {
|
for(int i = 0; i < mItem.length; i++) {
|
||||||
mItem[i] = new MenuItem(bar, SWT.CASCADE);
|
mItem[i] = new MenuItem(bar, SWT.CASCADE);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user