diff --git a/annotations/AtUnitComposition.java b/annotations/AtUnitComposition.java index 5c70b99b..3f92eddd 100644 --- a/annotations/AtUnitComposition.java +++ b/annotations/AtUnitComposition.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Creating non-embedded tests. package annotations; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitComposition { @@ -18,8 +18,7 @@ public class AtUnitComposition { } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit " + - " AtUnitComposition"); + "java onjava.atunit.AtUnit AtUnitComposition.class"); } } /* Output: diff --git a/annotations/AtUnitExample1.java b/annotations/AtUnitExample1.java index 5ab535a2..c061a416 100644 --- a/annotations/AtUnitExample1.java +++ b/annotations/AtUnitExample1.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package annotations; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitExample1 { @@ -24,7 +24,7 @@ public class AtUnitExample1 { @Test boolean anotherDisappointment() { return false; } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit AtUnitExample1"); + "java onjava.atunit.AtUnit AtUnitExample1.class"); } } /* Output: diff --git a/annotations/AtUnitExample2.java b/annotations/AtUnitExample2.java index 0138c25d..c1e013bd 100644 --- a/annotations/AtUnitExample2.java +++ b/annotations/AtUnitExample2.java @@ -5,7 +5,7 @@ // Assertions and exceptions can be used in @Tests. package annotations; import java.io.*; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitExample2 { @@ -32,7 +32,7 @@ public class AtUnitExample2 { } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit AtUnitExample2"); + "java onjava.atunit.AtUnit AtUnitExample2.class"); } } /* Output: diff --git a/annotations/AtUnitExample3.java b/annotations/AtUnitExample3.java index 4b904bf8..cdb48db5 100644 --- a/annotations/AtUnitExample3.java +++ b/annotations/AtUnitExample3.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package annotations; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitExample3 { @@ -27,7 +27,7 @@ public class AtUnitExample3 { @Test boolean m2() { return methodTwo() == 2; } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit AtUnitExample3"); + "java onjava.atunit.AtUnit AtUnitExample3.class"); } } /* Output: diff --git a/annotations/AtUnitExample4.java b/annotations/AtUnitExample4.java index f213844e..56b22a84 100644 --- a/annotations/AtUnitExample4.java +++ b/annotations/AtUnitExample4.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package annotations; import java.util.*; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitExample4 { @@ -58,7 +58,7 @@ public class AtUnitExample4 { public static void main(String[] args) throws Exception { System.out.println("starting"); OSExecute.command( - "java com.mindviewinc.atunit.AtUnit AtUnitExample4"); + "java onjava.atunit.AtUnit AtUnitExample4.class"); } } /* Output: diff --git a/annotations/AtUnitExample5.java b/annotations/AtUnitExample5.java index 6498a58b..8d4bfe7e 100644 --- a/annotations/AtUnitExample5.java +++ b/annotations/AtUnitExample5.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package annotations; import java.io.*; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitExample5 { @@ -42,7 +42,7 @@ public class AtUnitExample5 { } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit AtUnitExample5"); + "java onjava.atunit.AtUnit AtUnitExample5.class"); } } /* Output: diff --git a/annotations/AtUnitExternalTest.java b/annotations/AtUnitExternalTest.java index 6b382083..3db4db1d 100644 --- a/annotations/AtUnitExternalTest.java +++ b/annotations/AtUnitExternalTest.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Creating non-embedded tests. package annotations; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class AtUnitExternalTest extends AtUnitExample1 { @@ -14,8 +14,7 @@ public class AtUnitExternalTest extends AtUnitExample1 { @Test boolean _methodTwo() { return methodTwo() == 2; } public static void main(String[] args) throws Exception{ OSExecute.command( - "java com.mindviewinc.atunit.AtUnit " + - "AtUnitExternalTest"); + "java onjava.atunit.AtUnit AtUnitExternalTest.class"); } } /* Output: diff --git a/annotations/HashSetTest.java b/annotations/HashSetTest.java index eaf3d94f..8e70fb1f 100644 --- a/annotations/HashSetTest.java +++ b/annotations/HashSetTest.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package annotations; import java.util.*; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class HashSetTest { @@ -23,7 +23,7 @@ public class HashSetTest { } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit HashSetTest"); + "java onjava.atunit.AtUnit HashSetTest.class"); } } /* Output: diff --git a/annotations/StackLStringTest.java b/annotations/StackLStringTest.java index 6f2bbafe..19596565 100644 --- a/annotations/StackLStringTest.java +++ b/annotations/StackLStringTest.java @@ -4,7 +4,7 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Applying @Unit to generics. package annotations; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; import onjava.*; public class StackLStringTest extends StackL { @@ -28,8 +28,7 @@ public class StackLStringTest extends StackL { } public static void main(String[] args) throws Exception { OSExecute.command( - "java com.mindviewinc.atunit.AtUnit " + - "StackLStringTest"); + "java onjava.atunit.AtUnit StackLStringTest.class"); } } /* Output: diff --git a/annotations/Testable.java b/annotations/Testable.java index b0a4fd1f..68dc8cd4 100644 --- a/annotations/Testable.java +++ b/annotations/Testable.java @@ -3,7 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. package annotations; -import com.mindviewinc.atunit.*; +import onjava.atunit.*; public class Testable { public void execute() { diff --git a/com/build.xml b/com/build.xml index 4429a242..67ff4a5d 100644 --- a/com/build.xml +++ b/com/build.xml @@ -7,8 +7,6 @@ - - diff --git a/containers/UniqueWords.java b/containers/UniqueWords.java index 1b23e9eb..a7c890c4 100644 --- a/containers/UniqueWords.java +++ b/containers/UniqueWords.java @@ -3,20 +3,25 @@ // 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 onjava.*; +import java.nio.file.*; public class UniqueWords { - public static void main(String[] args) { - Set words = new TreeSet<>( - new TextFile("SetOperations.java", "\\W+")); + public static void main(String[] args) throws Exception { + List lines = + Files.readAllLines(Paths.get("SetOperations.java")); + Set 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); } } /* Output: [A, B, C, Collections, D, E, F, G, H, HashSet, I, J, K, L, -M, N, Output, Print, Set, SetOperations, String, X, Y, Z, -add, addAll, added, args, class, com, containers, contains, -containsAll, false, from, import, in, java, main, -mindviewinc, new, print, public, remove, removeAll, -removed, set1, set2, split, static, to, true, util, void] +M, N, Output, Set, SetOperations, String, System, X, Y, Z, +add, addAll, added, args, class, containers, contains, +containsAll, false, from, import, in, java, main, new, out, +println, public, remove, removeAll, removed, set1, set2, +split, static, to, true, util, void] */ diff --git a/containers/UniqueWordsAlphabetic.java b/containers/UniqueWordsAlphabetic.java index e95c006e..b888dd9c 100644 --- a/containers/UniqueWordsAlphabetic.java +++ b/containers/UniqueWordsAlphabetic.java @@ -4,22 +4,26 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Producing an alphabetic listing. import java.util.*; -import onjava.*; +import java.nio.file.*; public class UniqueWordsAlphabetic { - public static void main(String[] args) { + public static void main(String[] args) throws Exception { + List lines = + Files.readAllLines(Paths.get("SetOperations.java")); Set words = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); - words.addAll( - new TextFile("SetOperations.java", "\\W+")); + for(String line : lines) + for(String word : line.split("\\W+")) + if(word.trim().length() > 0) + words.add(word); System.out.println(words); } } /* Output: [A, add, addAll, added, args, B, C, class, Collections, -com, containers, contains, containsAll, D, E, F, false, -from, G, H, HashSet, I, import, in, J, java, K, L, M, main, -mindviewinc, N, new, Output, Print, public, remove, -removeAll, removed, Set, set1, set2, SetOperations, split, -static, String, to, true, util, void, X, Y, Z] +containers, contains, containsAll, D, E, F, false, from, G, +H, HashSet, I, import, in, J, java, K, L, M, main, N, new, +out, Output, println, public, remove, removeAll, removed, +Set, set1, set2, SetOperations, split, static, String, +System, to, true, util, void, X, Y, Z] */ diff --git a/enums/VendingMachine.java b/enums/VendingMachine.java index 043a18ef..536f99e2 100644 --- a/enums/VendingMachine.java +++ b/enums/VendingMachine.java @@ -4,8 +4,10 @@ // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // {Args: VendingMachineInput.txt} import java.util.*; +import java.io.IOException; import java.util.function.*; -import onjava.*; +import java.nio.file.*; +import java.util.stream.*; enum Category { MONEY(Input.NICKEL, Input.DIME, @@ -130,8 +132,16 @@ class RandomInputSupplier implements Supplier { class FileInputSupplier implements Supplier { private Iterator input; public FileInputSupplier(String fileName) { - // Skip the comment line in the input file: - input = new TextFile(fileName, ";").listIterator(1); + try { + 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 public Input get() { @@ -143,12 +153,12 @@ class FileInputSupplier implements Supplier { /* Output: 25 50 -Insufficient money for CHIPS -50 -150 -250 +75 +here is your CHIPS +0 +100 +200 here is your TOOTHPASTE -Your change: 50 0 25 35 diff --git a/files/AddAndSubtractPaths.java b/files/AddAndSubtractPaths.java index 3adddd91..95d61dd6 100644 --- a/files/AddAndSubtractPaths.java +++ b/files/AddAndSubtractPaths.java @@ -3,6 +3,7 @@ // 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.*; +import java.io.IOException; public class AddAndSubtractPaths { static Path base = Paths.get("..", "..", "..") @@ -14,6 +15,11 @@ public class AddAndSubtractPaths { base.relativize(result)); else 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) { System.out.println(System.getProperty("os.name")); @@ -41,6 +47,7 @@ public class AddAndSubtractPaths { Path p5 = Paths.get("").toAbsolutePath(); show(9, p5); show(10, p5.resolveSibling("strings")); + show(11, Paths.get("nonexistent")); } } /* Output: @@ -48,13 +55,32 @@ Windows 10 C:\Users\Bruce\Documents\Git (1)r on- java\ExtractedExamples\files\AddAndSubtractPaths.java +RealPath: C:\Users\Bruce\Documents\Git\on- +java\ExtractedExamples\files\AddAndSubtractPaths.java (2)r on-java\ExtractedExamples\strings\..\files +RealPath: C:\Users\Bruce\Documents\Git\on- +java\ExtractedExamples\files (3)r on-java\ExtractedExamples\files +RealPath: C:\Users\Bruce\Documents\Git\on- +java\ExtractedExamples\files (4) ..\.. +RealPath: C:\Users\Bruce\Documents\Git\on-java (5) ..\.. +RealPath: C:\Users\Bruce\Documents\Git\on-java (6)r on-java +RealPath: C:\Users\Bruce\Documents\Git\on-java (7)r on-java\ExtractedExamples\files\.\..\.. +RealPath: C:\Users\Bruce\Documents\Git\on-java (8)r on-java +RealPath: C:\Users\Bruce\Documents\Git\on-java (9)r on-java\ExtractedExamples\files +RealPath: C:\Users\Bruce\Documents\Git\on- +java\ExtractedExamples\files (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 */ diff --git a/files/DirList.java b/files/DirList.java deleted file mode 100644 index eab61114..00000000 --- a/files/DirList.java +++ /dev/null @@ -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 -*/ diff --git a/files/DirList2.java b/files/DirList2.java deleted file mode 100644 index 7070a7e7..00000000 --- a/files/DirList2.java +++ /dev/null @@ -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 -*/ diff --git a/files/DirList3.java b/files/DirList3.java deleted file mode 100644 index 0018ac22..00000000 --- a/files/DirList3.java +++ /dev/null @@ -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 -*/ diff --git a/files/Directories.java b/files/Directories.java new file mode 100644 index 00000000..18354dbc --- /dev/null +++ b/files/Directories.java @@ -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 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 +*/ diff --git a/files/DirectoryDemo.java b/files/DirectoryDemo.java deleted file mode 100644 index 045b9fb0..00000000 --- a/files/DirectoryDemo.java +++ /dev/null @@ -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 -*/ diff --git a/files/Find.java b/files/Find.java new file mode 100644 index 00000000..90aa99ee --- /dev/null +++ b/files/Find.java @@ -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 +*/ diff --git a/files/ListOfLines.java b/files/ListOfLines.java new file mode 100644 index 00000000..95d565bf --- /dev/null +++ b/files/ListOfLines.java @@ -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 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 +*/ diff --git a/files/MakeDirectories.java b/files/MakeDirectories.java deleted file mode 100644 index 80f0a506..00000000 --- a/files/MakeDirectories.java +++ /dev/null @@ -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 -*/ diff --git a/files/PathWatcher.java b/files/PathWatcher.java new file mode 100644 index 00000000..8b5d7d7f --- /dev/null +++ b/files/PathWatcher.java @@ -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 +*/ diff --git a/files/ReadLineStream.java b/files/ReadLineStream.java new file mode 100644 index 00000000..2bc89f71 --- /dev/null +++ b/files/ReadLineStream.java @@ -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)); +*/ diff --git a/files/StreamInAndOut.java b/files/StreamInAndOut.java new file mode 100644 index 00000000..0dd9ee30 --- /dev/null +++ b/files/StreamInAndOut.java @@ -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 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); + } + } +} diff --git a/files/TreeWatcher.java b/files/TreeWatcher.java new file mode 100644 index 00000000..476a7811 --- /dev/null +++ b/files/TreeWatcher.java @@ -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 +*/ diff --git a/files/Writing.java b/files/Writing.java new file mode 100644 index 00000000..2aa0682d --- /dev/null +++ b/files/Writing.java @@ -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 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 +*/ diff --git a/files/build.xml b/files/build.xml index 166b2be7..45d88376 100644 --- a/files/build.xml +++ b/files/build.xml @@ -8,15 +8,18 @@ - - - - + - + + + + + + + diff --git a/onjava/BinaryFile.java b/onjava/BinaryFile.java deleted file mode 100644 index b6525de1..00000000 --- a/onjava/BinaryFile.java +++ /dev/null @@ -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()); - } -} diff --git a/onjava/Directory.java b/onjava/Directory.java deleted file mode 100644 index e3f441cc..00000000 --- a/onjava/Directory.java +++ /dev/null @@ -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 { - public List files = new ArrayList<>(); - public List dirs = new ArrayList<>(); - // The default iterable element is the file list: - @Override - public Iterator 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 - ... -*/ diff --git a/onjava/PPrint.java b/onjava/PPrint.java deleted file mode 100644 index b80cdb23..00000000 --- a/onjava/PPrint.java +++ /dev/null @@ -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))); - } -} diff --git a/onjava/ProcessFiles.java b/onjava/ProcessFiles.java index e5818915..1e30bb35 100644 --- a/onjava/ProcessFiles.java +++ b/onjava/ProcessFiles.java @@ -5,6 +5,7 @@ // {ValidateByHand} package onjava; import java.io.*; +import java.nio.file.*; public class ProcessFiles { public interface Strategy { @@ -39,9 +40,11 @@ public class ProcessFiles { } public void processDirectoryTree(File root) throws IOException { - for(File file : Directory.walk( - root.getAbsolutePath(), ".*\\." + ext)) - strategy.process(file.getCanonicalFile()); + PathMatcher matcher = FileSystems.getDefault() + .getPathMatcher("glob:**/*.{" + ext + "}"); + Files.walk(root.toPath()) + .filter(matcher::matches) + .forEach(p -> strategy.process(p.toFile())); } // Demonstration of how to use it: public static void main(String[] args) { diff --git a/onjava/RmDir.java b/onjava/RmDir.java new file mode 100644 index 00000000..84a2e30a --- /dev/null +++ b/onjava/RmDir.java @@ -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(){ + @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; + } + }); + } +} diff --git a/onjava/TextFile.java b/onjava/TextFile.java deleted file mode 100644 index 8de3567f..00000000 --- a/onjava/TextFile.java +++ /dev/null @@ -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 { - // 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 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] -*/ diff --git a/com/mindviewinc/atunit/AtUnit.java b/onjava/atunit/AtUnit.java similarity index 94% rename from com/mindviewinc/atunit/AtUnit.java rename to onjava/atunit/AtUnit.java index f71c8cbb..7758a034 100644 --- a/com/mindviewinc/atunit/AtUnit.java +++ b/onjava/atunit/AtUnit.java @@ -1,12 +1,14 @@ -// com/mindviewinc/atunit/AtUnit.java +// onjava/atunit/AtUnit.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. // An annotation-based unit-test framework. -package com.mindviewinc.atunit; +package onjava.atunit; import java.lang.reflect.*; import java.io.*; import java.util.*; +import java.nio.file.*; +import java.util.stream.*; import onjava.*; public class AtUnit implements ProcessFiles.Strategy { @@ -32,7 +34,10 @@ public class AtUnit implements ProcessFiles.Strategy { public void process(File cFile) { try { String cName = ClassNameFinder.thisClass( - BinaryFile.read(cFile)); + Files.readAllBytes(cFile.toPath())); + if(!cName.startsWith("public:")) + return; + cName = cName.split(":")[1]; if(!cName.contains(".")) return; // Ignore unpackaged classes testClass = Class.forName(cName); @@ -95,7 +100,8 @@ public class AtUnit implements ProcessFiles.Strategy { } } } - static class TestMethods extends ArrayList { + public static + class TestMethods extends ArrayList { void addIfTestMethod(Method m) { if(m.getAnnotation(Test.class) == null) return; @@ -158,6 +164,3 @@ public class AtUnit implements ProcessFiles.Strategy { } } } -/* Output: -OK (0 tests) -*/ diff --git a/com/mindviewinc/atunit/ClassNameFinder.java b/onjava/atunit/ClassNameFinder.java similarity index 64% rename from com/mindviewinc/atunit/ClassNameFinder.java rename to onjava/atunit/ClassNameFinder.java index 5bfd563c..2021b709 100644 --- a/com/mindviewinc/atunit/ClassNameFinder.java +++ b/onjava/atunit/ClassNameFinder.java @@ -1,9 +1,10 @@ -// com/mindviewinc/atunit/ClassNameFinder.java +// onjava/atunit/ClassNameFinder.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 com.mindviewinc.atunit; +package onjava.atunit; import java.io.*; +import java.nio.file.*; import java.util.*; import onjava.*; @@ -21,7 +22,7 @@ public class ClassNameFinder { int[] constant_pool = new int[constant_pool_count]; for(int i = 1; i < constant_pool_count; i++) { int tag = data.read(); - int tableSize; + // int tableSize; switch(tag) { case 1: // UTF int length = data.readShort(); @@ -49,16 +50,26 @@ public class ClassNameFinder { case 10: // METHOD_REF case 11: // INTERFACE_METHOD_REF case 12: // NAME_AND_TYPE + case 18: // Invoke Dynamic data.readInt(); // discard 4 bytes; break; + case 15: // Method Handle + data.readByte(); + data.readShort(); + break; + case 16: // Method Type + data.readShort(); + break; default: throw new RuntimeException("Bad tag " + tag); } } short access_flags = data.readShort(); + String access = (access_flags & 0x0001) == 0 ? + "nonpublic:" : "public:"; int this_class = data.readShort(); int super_class = data.readShort(); - return classNameTable.get( + return access + classNameTable.get( offsetTable.get(this_class)).replace('/', '.'); } catch(IOException | RuntimeException e) { throw new RuntimeException(e); @@ -66,23 +77,33 @@ public class ClassNameFinder { } // Demonstration: public static void main(String[] args) throws Exception { - if(args.length > 0) { - for(String arg : args) - System.out.println( - thisClass(BinaryFile.read(new File(arg)))); - } else - // Walk the entire tree: <* Use NIO2 here *> - for(File klass : Directory.walk(".", ".*\\.class")) - System.out.println( - thisClass(BinaryFile.read(klass))); + PathMatcher matcher = FileSystems.getDefault() + .getPathMatcher("glob:**/*.class"); + // Walk the entire tree: + Files.walk(Paths.get(".")) + .filter(matcher::matches) + //.peek(System.out::println) + .map(p -> { + try { + 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: -com.mindviewinc.atunit.AtUnit$TestMethods -com.mindviewinc.atunit.AtUnit -com.mindviewinc.atunit.ClassNameFinder -com.mindviewinc.atunit.Test -com.mindviewinc.atunit.TestObjectCleanup -com.mindviewinc.atunit.TestObjectCreate -com.mindviewinc.atunit.TestProperty +onjava.atunit.AtUnit$TestMethods +onjava.atunit.AtUnit +onjava.atunit.ClassNameFinder +onjava.atunit.Test +onjava.atunit.TestObjectCleanup +onjava.atunit.TestObjectCreate +onjava.atunit.TestProperty */ diff --git a/com/mindviewinc/atunit/Test.java b/onjava/atunit/Test.java similarity index 82% rename from com/mindviewinc/atunit/Test.java rename to onjava/atunit/Test.java index a9bfc7fa..dc631344 100644 --- a/com/mindviewinc/atunit/Test.java +++ b/onjava/atunit/Test.java @@ -1,9 +1,9 @@ -// com/mindviewinc/atunit/Test.java +// onjava/atunit/Test.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. // The @Test tag. -package com.mindviewinc.atunit; +package onjava.atunit; import java.lang.annotation.*; @Target(ElementType.METHOD) diff --git a/com/mindviewinc/atunit/TestObjectCleanup.java b/onjava/atunit/TestObjectCleanup.java similarity index 81% rename from com/mindviewinc/atunit/TestObjectCleanup.java rename to onjava/atunit/TestObjectCleanup.java index e34bc074..384f736e 100644 --- a/com/mindviewinc/atunit/TestObjectCleanup.java +++ b/onjava/atunit/TestObjectCleanup.java @@ -1,9 +1,9 @@ -// com/mindviewinc/atunit/TestObjectCleanup.java +// onjava/atunit/TestObjectCleanup.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. // The @Unit @TestObjectCleanup tag. -package com.mindviewinc.atunit; +package onjava.atunit; import java.lang.annotation.*; @Target(ElementType.METHOD) diff --git a/com/mindviewinc/atunit/TestObjectCreate.java b/onjava/atunit/TestObjectCreate.java similarity index 81% rename from com/mindviewinc/atunit/TestObjectCreate.java rename to onjava/atunit/TestObjectCreate.java index a60bcb16..c0364d81 100644 --- a/com/mindviewinc/atunit/TestObjectCreate.java +++ b/onjava/atunit/TestObjectCreate.java @@ -1,9 +1,9 @@ -// com/mindviewinc/atunit/TestObjectCreate.java +// onjava/atunit/TestObjectCreate.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. // The @Unit @TestObjectCreate tag. -package com.mindviewinc.atunit; +package onjava.atunit; import java.lang.annotation.*; @Target(ElementType.METHOD) diff --git a/com/mindviewinc/atunit/TestProperty.java b/onjava/atunit/TestProperty.java similarity index 84% rename from com/mindviewinc/atunit/TestProperty.java rename to onjava/atunit/TestProperty.java index beb6e062..17e8e3db 100644 --- a/com/mindviewinc/atunit/TestProperty.java +++ b/onjava/atunit/TestProperty.java @@ -1,9 +1,9 @@ -// com/mindviewinc/atunit/TestProperty.java +// onjava/atunit/TestProperty.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. // The @Unit @TestProperty tag. -package com.mindviewinc.atunit; +package onjava.atunit; import java.lang.annotation.*; // Both fields and methods can be tagged as properties: diff --git a/onjava/build.xml b/onjava/build.xml index 371f1f24..0f33be28 100644 --- a/onjava/build.xml +++ b/onjava/build.xml @@ -11,9 +11,9 @@ - - + + diff --git a/operators/Literals.java b/operators/Literals.java index 6ec217d7..124d28ff 100644 --- a/operators/Literals.java +++ b/operators/Literals.java @@ -27,16 +27,16 @@ public class Literals { long n2 = 200l; // long suffix (but can be confusing) long n3 = 200; // Java 7 Binary Literals: - byte blb = (byte)0b00110101; + byte blb = (byte)0b00110101; System.out.println( "blb: " + Integer.toBinaryString(blb)); short bls = (short)0B0010111110101111; System.out.println( "bls: " + Integer.toBinaryString(bls)); - int bli = 0b00101111101011111010111110101111; + int bli = 0b00101111101011111010111110101111; System.out.println( "bli: " + Integer.toBinaryString(bli)); - long bll = 0b00101111101011111010111110101111; + long bll = 0b00101111101011111010111110101111; System.out.println( "bll: " + Long.toBinaryString(bll)); float f1 = 1; diff --git a/operators/Underscores.java b/operators/Underscores.java new file mode 100644 index 00000000..92163322 --- /dev/null +++ b/operators/Underscores.java @@ -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 +*/ diff --git a/operators/build.xml b/operators/build.xml index dd288cd3..a4e7d522 100644 --- a/operators/build.xml +++ b/operators/build.xml @@ -26,6 +26,7 @@ + diff --git a/serialization/Logon.java b/serialization/Logon.java index a364a5f7..a94b40ff 100644 --- a/serialization/Logon.java +++ b/serialization/Logon.java @@ -3,6 +3,7 @@ // We make no guarantees that this code is fit for any purpose. // Visit http://mindviewinc.com/Books/OnJava/ for more book information. // Demonstrates the "transient" keyword. +// {IgnoreReturnValue} import java.util.concurrent.*; import java.io.*; import java.util.*; diff --git a/serialization/build.xml b/serialization/build.xml index d79fc7ef..7c29e654 100644 --- a/serialization/build.xml +++ b/serialization/build.xml @@ -12,7 +12,7 @@ - + diff --git a/streams/FileToWords.java b/streams/FileToWords.java index 9aad9425..2f6bd53b 100644 --- a/streams/FileToWords.java +++ b/streams/FileToWords.java @@ -12,6 +12,6 @@ public class FileToWords { return Files.lines(Paths.get(filePath)) .skip(1) // First (comment) line .flatMap(line -> - Pattern.compile("[ .,?]+").splitAsStream(line)); + Pattern.compile("\\W+").splitAsStream(line)); } } diff --git a/streams/TreeSetOfWords.java b/streams/TreeSetOfWords.java new file mode 100644 index 00000000..1547f6aa --- /dev/null +++ b/streams/TreeSetOfWords.java @@ -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 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] +*/ diff --git a/streams/build.xml b/streams/build.xml index 755be3c5..8f44f3ae 100644 --- a/streams/build.xml +++ b/streams/build.xml @@ -50,6 +50,7 @@ + diff --git a/strings/JGrep.java b/strings/JGrep.java index 736182c8..1bd00c3e 100644 --- a/strings/JGrep.java +++ b/strings/JGrep.java @@ -5,7 +5,8 @@ // A very simple version of the "grep" program. // {Args: JGrep.java 'void|int|String'} import java.util.regex.*; -import onjava.*; +import java.nio.file.*; +import java.util.stream.*; public class JGrep { public static void main(String[] args) throws Exception { @@ -17,7 +18,8 @@ public class JGrep { // Iterate through the lines of the input file: int index = 0; Matcher m = p.matcher(""); - for(String line : new TextFile(args[0])) { + for(String line : + Files.readAllLines(Paths.get(args[0]))) { m.reset(line); while(m.find()) System.out.println(index++ + ": " + @@ -26,28 +28,14 @@ public class JGrep { } } /* Output: -0: 'void: 21 -1: int: 27 -2: String': 31 -3: int: 19 -4: int: 4 -5: int: 21 -6: 'void: 3 -7: int: 3 -8: String': 3 -9: int: 3 -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 +Here's a block of text to use as input to +the regular expression matcher. Note that we +first extract the block of text by looking for +the special delimiters, then process the +extracted block. +H(VOWEL1)rE's A blOck Of tExt tO UsE As InpUt tO +thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE +fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr +thE spEcIAl dElImItErs, thEn prOcEss thE +ExtrActEd blOck. */ diff --git a/strings/TheReplacements.java b/strings/TheReplacements.java index 9789b50f..49a9722b 100644 --- a/strings/TheReplacements.java +++ b/strings/TheReplacements.java @@ -3,7 +3,8 @@ // 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.regex.*; -import onjava.*; +import java.nio.file.*; +import java.util.stream.*; /*! Here's a block of text to use as input to the regular expression matcher. Note that we @@ -13,11 +14,12 @@ import onjava.*; public class TheReplacements { 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: - Matcher mInput = - Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL) - .matcher(s); + Matcher mInput = Pattern.compile( + "/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s); if(mInput.find()) s = mInput.group(1); // Captured by parentheses // Replace two or more spaces with a single space: diff --git a/swt/Menus.java b/swt/Menus.java index cc2dd847..502ac18a 100644 --- a/swt/Menus.java +++ b/swt/Menus.java @@ -7,7 +7,9 @@ import swt.util.*; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import java.util.*; -import onjava.*; +import java.io.IOException; +import java.nio.file.*; +import java.util.stream.*; public class Menus implements SWTApplication { private static Shell shell; @@ -16,11 +18,17 @@ public class Menus implements SWTApplication { shell = parent.getShell(); Menu bar = new Menu(shell, SWT.BAR); shell.setMenuBar(bar); - Set words = new TreeSet<>( - new TextFile("Menus.java", "\\W+")); + Set words = null; + 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 it = words.iterator(); - while(it.next().matches("[0-9]+")) - ; // Move past the numbers. MenuItem[] mItem = new MenuItem[7]; for(int i = 0; i < mItem.length; i++) { mItem[i] = new MenuItem(bar, SWT.CASCADE);