diff --git a/.idea/.name b/.idea/.name
new file mode 100644
index 0000000..c6ddec8
--- /dev/null
+++ b/.idea/.name
@@ -0,0 +1 @@
+com.helmet
\ No newline at end of file
diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml
new file mode 100644
index 0000000..5a896e4
--- /dev/null
+++ b/.idea/codeStyleSettings.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..51443f4
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml
new file mode 100644
index 0000000..e7bedf3
--- /dev/null
+++ b/.idea/copyright/profiles_settings.xml
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
new file mode 100644
index 0000000..97626ba
--- /dev/null
+++ b/.idea/encodings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/gradle.xml b/.idea/gradle.xml
new file mode 100644
index 0000000..e55b04d
--- /dev/null
+++ b/.idea/gradle.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Gradle__asm_asm_3_3_1.xml b/.idea/libraries/Gradle__asm_asm_3_3_1.xml
new file mode 100644
index 0000000..0cf5e35
--- /dev/null
+++ b/.idea/libraries/Gradle__asm_asm_3_3_1.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Gradle__cglib_cglib_2_2_2.xml b/.idea/libraries/Gradle__cglib_cglib_2_2_2.xml
new file mode 100644
index 0000000..27461a0
--- /dev/null
+++ b/.idea/libraries/Gradle__cglib_cglib_2_2_2.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Gradle__commons_io_commons_io_2_5.xml b/.idea/libraries/Gradle__commons_io_commons_io_2_5.xml
new file mode 100644
index 0000000..12ab8e6
--- /dev/null
+++ b/.idea/libraries/Gradle__commons_io_commons_io_2_5.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Gradle__junit_junit_4_11.xml b/.idea/libraries/Gradle__junit_junit_4_11.xml
new file mode 100644
index 0000000..dc26b34
--- /dev/null
+++ b/.idea/libraries/Gradle__junit_junit_4_11.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Gradle__org_hamcrest_hamcrest_core_1_3.xml b/.idea/libraries/Gradle__org_hamcrest_hamcrest_core_1_3.xml
new file mode 100644
index 0000000..8262f72
--- /dev/null
+++ b/.idea/libraries/Gradle__org_hamcrest_hamcrest_core_1_3.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..041c3ac
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..cae8886
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules/com.helmet.iml b/.idea/modules/com.helmet.iml
new file mode 100644
index 0000000..d3a7931
--- /dev/null
+++ b/.idea/modules/com.helmet.iml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules/com.helmet_main.iml b/.idea/modules/com.helmet_main.iml
new file mode 100644
index 0000000..17be7ac
--- /dev/null
+++ b/.idea/modules/com.helmet_main.iml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules/com.helmet_test.iml b/.idea/modules/com.helmet_test.iml
new file mode 100644
index 0000000..3a05699
--- /dev/null
+++ b/.idea/modules/com.helmet_test.iml
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..c4a2e41
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index 13ae18b..d9627e2 100644
--- a/build.gradle
+++ b/build.gradle
@@ -13,4 +13,5 @@ dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile("cglib:cglib:2.2.2")
+ compile group: 'commons-io', name: 'commons-io', version: '2.5'
}
diff --git a/img/11.gif b/img/11.gif
new file mode 100644
index 0000000..a2d2430
Binary files /dev/null and b/img/11.gif differ
diff --git a/img/2.png b/img/2.png
index a46940e..a2d2430 100644
Binary files a/img/2.png and b/img/2.png differ
diff --git a/src/main/java/arraysTest/TestArrays.java b/src/main/java/arraysTest/TestArrays.java
new file mode 100644
index 0000000..01a3da1
--- /dev/null
+++ b/src/main/java/arraysTest/TestArrays.java
@@ -0,0 +1,51 @@
+package arraysTest;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+
+/**
+ * Created by helmeter on 7/2/16.
+ */
+public class TestArrays {
+
+ public static void main(String[] args) {
+ int[] testString = {3, 4, 1, 2, 5, 10};
+ //1,2,3,4,5,10
+ Arrays.sort(testString);
+ int k = Arrays.binarySearch(testString, 0, 5, 3);
+
+ System.out.println(k);
+ String[] names = {"Liz", "John", "Eric", "Alan"};
+//只排序前两个
+//[John, Liz, Eric, Alan]
+ Arrays.sort(names, 0, 2);
+//全部排序
+//[Alan, Eric, John, Liz]
+ Arrays.sort(names,
+// String.CASE_INSENSITIVE_ORDER
+ Collections.reverseOrder()
+// new Comparator() {
+// public int compare(String o1, String o2) {
+// return o1.compareTo(o2);
+//
+// }
+// }
+ );
+ String[] copy = Arrays.copyOfRange(names, 1, 3);
+
+ System.out.println(Arrays.toString(names));
+
+ int[][] stuGrades = {{80, 81, 82}, {84, 85, 86}, {87, 88, 89}};
+
+ System.out.println(Arrays.deepToString(stuGrades));
+
+
+ String[] names1 = { "Eric", "John", "Alan", "Liz" };
+
+ String[] names2 = { "Eric", "John","Liz","Alan" };
+
+ System.out.println(Arrays.equals(names1, names2));
+
+ }
+}
diff --git a/src/main/java/concurrent/CachedThreadPool.java b/src/main/java/concurrent/CachedThreadPool.java
deleted file mode 100755
index 041f5d4..0000000
--- a/src/main/java/concurrent/CachedThreadPool.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package concurrent;//: concurrency/CachedThreadPool.java
-import java.util.concurrent.*;
-
-public class CachedThreadPool {
- public static void main(String[] args) {
- ExecutorService exec = Executors.newCachedThreadPool();
- for(int i = 0; i < 5; i++)
- exec.execute(new LiftOff());
- exec.shutdown();
- }
-} /* Output: (Sample)
-#0(9), #0(8), #1(9), #2(9), #3(9), #4(9), #0(7), #1(8), #2(8), #3(8), #4(8), #0(6), #1(7), #2(7), #3(7), #4(7), #0(5), #1(6), #2(6), #3(6), #4(6), #0(4), #1(5), #2(5), #3(5), #4(5), #0(3), #1(4), #2(4), #3(4), #4(4), #0(2), #1(3), #2(3), #3(3), #4(3), #0(1), #1(2), #2(2), #3(2), #4(2), #0(Liftoff!), #1(1), #2(1), #3(1), #4(1), #1(Liftoff!), #2(Liftoff!), #3(Liftoff!), #4(Liftoff!),
-*///:~
diff --git a/src/main/java/io/Alien.java b/src/main/java/io/Alien.java
new file mode 100755
index 0000000..5a84044
--- /dev/null
+++ b/src/main/java/io/Alien.java
@@ -0,0 +1,4 @@
+package io;//: io/Alien.java
+// A serializable class.
+import java.io.*;
+public class Alien implements Serializable {} ///:~
diff --git a/src/main/java/io/AvailableCharSets.java b/src/main/java/io/AvailableCharSets.java
new file mode 100755
index 0000000..5259c5f
--- /dev/null
+++ b/src/main/java/io/AvailableCharSets.java
@@ -0,0 +1,36 @@
+package io;//: io/AvailableCharSets.java
+// Displays Charsets and aliases
+import java.nio.charset.*;
+import java.util.*;
+import static net.mindview.util.Print.*;
+
+public class AvailableCharSets {
+ public static void main(String[] args) {
+ SortedMap charSets =
+ Charset.availableCharsets();
+ Iterator it = charSets.keySet().iterator();
+ while(it.hasNext()) {
+ String csName = it.next();
+ printnb(csName);
+ Iterator aliases =
+ charSets.get(csName).aliases().iterator();
+ if(aliases.hasNext())
+ printnb(": ");
+ while(aliases.hasNext()) {
+ printnb(aliases.next());
+ if(aliases.hasNext())
+ printnb(", ");
+ }
+ print();
+ }
+ }
+} /* Output:
+Big5: csBig5
+Big5-HKSCS: big5-hkscs, big5hk, big5-hkscs:unicode3.0, big5hkscs, Big5_HKSCS
+EUC-JP: eucjis, x-eucjp, csEUCPkdFmtjapanese, eucjp, Extended_UNIX_Code_Packed_Format_for_Japanese, x-euc-jp, euc_jp
+EUC-KR: ksc5601, 5601, ksc5601_1987, ksc_5601, ksc5601-1987, euc_kr, ks_c_5601-1987, euckr, csEUCKR
+GB18030: gb18030-2000
+GB2312: gb2312-1980, gb2312, EUC_CN, gb2312-80, euc-cn, euccn, x-EUC-CN
+GBK: windows-936, CP936
+...
+*///:~
diff --git a/src/main/java/io/BasicFileOutput.java b/src/main/java/io/BasicFileOutput.java
new file mode 100755
index 0000000..2e897d5
--- /dev/null
+++ b/src/main/java/io/BasicFileOutput.java
@@ -0,0 +1,21 @@
+package io;//: io/BasicFileOutput.java
+import java.io.*;
+
+public class BasicFileOutput {
+ static String file = "BasicFileOutput.out";
+ public static void main(String[] args)
+ throws IOException {
+ BufferedReader in = new BufferedReader(
+ new StringReader(
+ BufferedInputFile.read("BasicFileOutput.java")));
+ PrintWriter out = new PrintWriter(
+ new BufferedWriter(new FileWriter(file)));
+ int lineCount = 1;
+ String s;
+ while((s = in.readLine()) != null )
+ out.println(lineCount++ + ": " + s);
+ out.close();
+ // Show the stored file:
+ System.out.println(BufferedInputFile.read(file));
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/Blip3.java b/src/main/java/io/Blip3.java
new file mode 100755
index 0000000..ee0ffac
--- /dev/null
+++ b/src/main/java/io/Blip3.java
@@ -0,0 +1,61 @@
+package io;//: io/Blip3.java
+// Reconstructing an externalizable object.
+import java.io.*;
+import static net.mindview.util.Print.*;
+
+public class Blip3 implements Externalizable {
+ private int i;
+ private String s; // No initialization
+ public Blip3() {
+ print("Blip3 Constructor");
+ // s, i not initialized
+ }
+ public Blip3(String x, int a) {
+ print("Blip3(String x, int a)");
+ s = x;
+ i = a;
+ // s & i initialized only in non-default constructor.
+ }
+ public String toString() { return s + i; }
+ public void writeExternal(ObjectOutput out)
+ throws IOException {
+ print("Blip3.writeExternal");
+ // You must do this:
+ out.writeObject(s);
+ out.writeInt(i);
+ }
+ public void readExternal(ObjectInput in)
+ throws IOException, ClassNotFoundException {
+ print("Blip3.readExternal");
+ // You must do this:
+ s = (String)in.readObject();
+ i = in.readInt();
+ }
+ public static void main(String[] args)
+ throws IOException, ClassNotFoundException {
+ print("Constructing objects:");
+ Blip3 b3 = new Blip3("A String ", 47);
+ print(b3);
+ ObjectOutputStream o = new ObjectOutputStream(
+ new FileOutputStream("Blip3.out"));
+ print("Saving object:");
+ o.writeObject(b3);
+ o.close();
+ // Now get it back:
+ ObjectInputStream in = new ObjectInputStream(
+ new FileInputStream("Blip3.out"));
+ print("Recovering b3:");
+ b3 = (Blip3)in.readObject();
+ print(b3);
+ }
+} /* Output:
+Constructing objects:
+Blip3(String x, int a)
+A String 47
+Saving object:
+Blip3.writeExternal
+Recovering b3:
+Blip3 Constructor
+Blip3.readExternal
+A String 47
+*///:~
diff --git a/src/main/java/io/Blips.java b/src/main/java/io/Blips.java
new file mode 100755
index 0000000..3e2fcb9
--- /dev/null
+++ b/src/main/java/io/Blips.java
@@ -0,0 +1,65 @@
+package io;//: io/Blips.java
+// Simple use of Externalizable & a pitfall.
+import java.io.*;
+import static net.mindview.util.Print.*;
+
+class Blip1 implements Externalizable {
+ public Blip1() {
+ print("Blip1 Constructor");
+ }
+ public void writeExternal(ObjectOutput out)
+ throws IOException {
+ print("Blip1.writeExternal");
+ }
+ public void readExternal(ObjectInput in)
+ throws IOException, ClassNotFoundException {
+ print("Blip1.readExternal");
+ }
+}
+
+class Blip2 implements Externalizable {
+ Blip2() {
+ print("Blip2 Constructor");
+ }
+ public void writeExternal(ObjectOutput out)
+ throws IOException {
+ print("Blip2.writeExternal");
+ }
+ public void readExternal(ObjectInput in)
+ throws IOException, ClassNotFoundException {
+ print("Blip2.readExternal");
+ }
+}
+
+public class Blips {
+ public static void main(String[] args)
+ throws IOException, ClassNotFoundException {
+ print("Constructing objects:");
+ Blip1 b1 = new Blip1();
+ Blip2 b2 = new Blip2();
+ ObjectOutputStream o = new ObjectOutputStream(
+ new FileOutputStream("Blips.out"));
+ print("Saving objects:");
+ o.writeObject(b1);
+ o.writeObject(b2);
+ o.close();
+ // Now get them back:
+ ObjectInputStream in = new ObjectInputStream(
+ new FileInputStream("Blips.out"));
+ print("Recovering b1:");
+ b1 = (Blip1)in.readObject();
+ // OOPS! Throws an exception:
+//! print("Recovering b2:");
+//! b2 = (Blip2)in.readObject();
+ }
+} /* Output:
+Constructing objects:
+Blip1 Constructor
+Blip2 Constructor
+Saving objects:
+Blip1.writeExternal
+Blip2.writeExternal
+Recovering b1:
+Blip1 Constructor
+Blip1.readExternal
+*///:~
diff --git a/src/main/java/io/BufferToText.java b/src/main/java/io/BufferToText.java
new file mode 100755
index 0000000..6adcd63
--- /dev/null
+++ b/src/main/java/io/BufferToText.java
@@ -0,0 +1,55 @@
+package io;//: io/BufferToText.java
+// Converting text to and from ByteBuffers
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+import java.io.*;
+
+public class BufferToText {
+ private static final int BSIZE = 1024;
+ public static void main(String[] args) throws Exception {
+ FileChannel fc =
+ new FileOutputStream("data2.txt").getChannel();
+ fc.write(ByteBuffer.wrap("Some text".getBytes()));
+ fc.close();
+ fc = new FileInputStream("data2.txt").getChannel();
+ ByteBuffer buff = ByteBuffer.allocate(BSIZE);
+ fc.read(buff);
+ buff.flip();
+ // Doesn't work:
+ System.out.println(buff.asCharBuffer());
+ // Decode using this system's default Charset:
+ buff.rewind();
+ String encoding = System.getProperty("file.encoding");
+ System.out.println("Decoded using " + encoding + ": "
+ + Charset.forName(encoding).decode(buff));
+ // Or, we could encode with something that will print:
+ fc = new FileOutputStream("data2.txt").getChannel();
+ fc.write(ByteBuffer.wrap(
+ "Some text".getBytes("UTF-16BE")));
+ fc.close();
+ // Now try reading again:
+ fc = new FileInputStream("data2.txt").getChannel();
+ buff.clear();
+ fc.read(buff);
+ buff.flip();
+ System.out.println(buff.asCharBuffer());
+ // Use a CharBuffer to write through:
+ fc = new FileOutputStream("data2.txt").getChannel();
+ buff = ByteBuffer.allocate(24); // More than needed
+ buff.asCharBuffer().put("Some text");
+ fc.write(buff);
+ fc.close();
+ // Read and display:
+ fc = new FileInputStream("data2.txt").getChannel();
+ buff.clear();
+ fc.read(buff);
+ buff.flip();
+ System.out.println(buff.asCharBuffer());
+ }
+} /* Output:
+????
+Decoded using Cp1252: Some text
+Some text
+Some text
+*///:~
diff --git a/src/main/java/io/BufferedInputFile.java b/src/main/java/io/BufferedInputFile.java
new file mode 100755
index 0000000..45b6c36
--- /dev/null
+++ b/src/main/java/io/BufferedInputFile.java
@@ -0,0 +1,22 @@
+package io;//: io/BufferedInputFile.java
+import java.io.*;
+
+public class BufferedInputFile {
+ // Throw exceptions to console:
+ public static String
+ read(String filename) throws IOException {
+ // Reading input by lines:
+ BufferedReader in = new BufferedReader(
+ new FileReader(filename));
+ String s;
+ StringBuilder sb = new StringBuilder();
+ while((s = in.readLine())!= null)
+ sb.append(s + "\n");
+ in.close();
+ return sb.toString();
+ }
+ public static void main(String[] args)
+ throws IOException {
+ System.out.print(read("img/student.txt"));
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/ChangeSystemOut.java b/src/main/java/io/ChangeSystemOut.java
new file mode 100755
index 0000000..1eeec88
--- /dev/null
+++ b/src/main/java/io/ChangeSystemOut.java
@@ -0,0 +1,12 @@
+package io;//: io/ChangeSystemOut.java
+// Turn System.out into a PrintWriter.
+import java.io.*;
+
+public class ChangeSystemOut {
+ public static void main(String[] args) {
+ PrintWriter out = new PrintWriter(System.out, true);
+ out.println("Hello, world");
+ }
+} /* Output:
+Hello, world
+*///:~
diff --git a/src/main/java/io/ChannelCopy.java b/src/main/java/io/ChannelCopy.java
new file mode 100755
index 0000000..c5519a1
--- /dev/null
+++ b/src/main/java/io/ChannelCopy.java
@@ -0,0 +1,25 @@
+package io;//: io/ChannelCopy.java
+// Copying a file using channels and buffers
+// {Args: ChannelCopy.java test.txt}
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class ChannelCopy {
+ private static final int BSIZE = 1024;
+ public static void main(String[] args) throws Exception {
+ if(args.length != 2) {
+ System.out.println("arguments: sourcefile destfile");
+ System.exit(1);
+ }
+ FileChannel
+ in = new FileInputStream(args[0]).getChannel(),
+ out = new FileOutputStream(args[1]).getChannel();
+ ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
+ while(in.read(buffer) != -1) {
+ buffer.flip(); // Prepare for writing
+ out.write(buffer);
+ buffer.clear(); // Prepare for reading
+ }
+ }
+} ///:~
diff --git a/src/main/java/io/DirList.java b/src/main/java/io/DirList.java
new file mode 100755
index 0000000..7a73eed
--- /dev/null
+++ b/src/main/java/io/DirList.java
@@ -0,0 +1,35 @@
+package io;//: io/DirList.java
+// 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);
+ }
+ public boolean accept(File dir, String name) {
+ return pattern.matcher(name).matches();
+ }
+} /* Output:
+DirectoryDemo.java
+DirList.java
+DirList2.java
+DirList3.java
+*///:~
diff --git a/src/main/java/io/DirList2.java b/src/main/java/io/DirList2.java
new file mode 100755
index 0000000..26adc57
--- /dev/null
+++ b/src/main/java/io/DirList2.java
@@ -0,0 +1,34 @@
+package io;//: io/DirList2.java
+// 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);
+ 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/src/main/java/io/DirList3.java b/src/main/java/io/DirList3.java
new file mode 100755
index 0000000..4a40ff1
--- /dev/null
+++ b/src/main/java/io/DirList3.java
@@ -0,0 +1,30 @@
+package io;//: io/DirList3.java
+// 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]);
+ 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/src/main/java/io/DirectoryDemo.java b/src/main/java/io/DirectoryDemo.java
new file mode 100755
index 0000000..864a8d3
--- /dev/null
+++ b/src/main/java/io/DirectoryDemo.java
@@ -0,0 +1,37 @@
+package io;//: io/DirectoryDemo.java
+// Sample use of Directory utilities.
+import java.io.*;
+import net.mindview.util.*;
+import static net.mindview.util.Print.*;
+
+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.*"))
+ print(file);
+ print("----------------------");
+ // All Java files beginning with 'T':
+ for(File file : Directory.walk(".", "T.*\\.java"))
+ print(file);
+ print("======================");
+ // Class files containing "Z" or "z":
+ for(File file : Directory.walk(".",".*[Zz].*\\.class"))
+ print(file);
+ }
+} /* Output: (Sample)
+[.\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/src/main/java/io/Echo.java b/src/main/java/io/Echo.java
new file mode 100755
index 0000000..1a79c93
--- /dev/null
+++ b/src/main/java/io/Echo.java
@@ -0,0 +1,16 @@
+package io;//: io/Echo.java
+// How to read from standard input.
+// {RunByHand}
+import java.io.*;
+
+public class Echo {
+ public static void main(String[] args)
+ throws IOException {
+ BufferedReader stdin = new BufferedReader(
+ new InputStreamReader(System.in));
+ String s;
+ while((s = stdin.readLine()) != null && s.length()!= 0)
+ System.out.println(s);
+ // An empty line or Ctrl-Z terminates the program
+ }
+} ///:~
diff --git a/src/main/java/io/Endians.java b/src/main/java/io/Endians.java
new file mode 100755
index 0000000..4523188
--- /dev/null
+++ b/src/main/java/io/Endians.java
@@ -0,0 +1,25 @@
+package io;//: io/Endians.java
+// Endian differences and data storage.
+import java.nio.*;
+import java.util.*;
+import static net.mindview.util.Print.*;
+
+public class Endians {
+ public static void main(String[] args) {
+ ByteBuffer bb = ByteBuffer.wrap(new byte[12]);
+ bb.asCharBuffer().put("abcdef");
+ print(Arrays.toString(bb.array()));
+ bb.rewind();
+ bb.order(ByteOrder.BIG_ENDIAN);
+ bb.asCharBuffer().put("abcdef");
+ print(Arrays.toString(bb.array()));
+ bb.rewind();
+ bb.order(ByteOrder.LITTLE_ENDIAN);
+ bb.asCharBuffer().put("abcdef");
+ print(Arrays.toString(bb.array()));
+ }
+} /* Output:
+[0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102]
+[0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102]
+[97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0]
+*///:~
diff --git a/src/main/java/io/FileCopy.java b/src/main/java/io/FileCopy.java
index 9c9360f..b96839b 100644
--- a/src/main/java/io/FileCopy.java
+++ b/src/main/java/io/FileCopy.java
@@ -11,7 +11,7 @@ public static void main(String[] args) {
InputStream input=null;
OutputStream out =null;
try {
- input=new FileInputStream("img/1.png");
+ input=new FileInputStream("img/11.gif");
out=new FileOutputStream("img/2.png"); //如果文件不存在会自动创建
while ((numberRead=input.read(buffer))!=-1) { //numberRead的目的在于防止最后一次读取的字节小于buffer长度,
diff --git a/src/main/java/io/FileLocking.java b/src/main/java/io/FileLocking.java
new file mode 100755
index 0000000..6132767
--- /dev/null
+++ b/src/main/java/io/FileLocking.java
@@ -0,0 +1,21 @@
+package io;//: io/FileLocking.java
+import java.nio.channels.*;
+import java.util.concurrent.*;
+import java.io.*;
+
+public class FileLocking {
+ public static void main(String[] args) throws Exception {
+ FileOutputStream fos= new FileOutputStream("file.txt");
+ FileLock fl = fos.getChannel().tryLock();
+ if(fl != null) {
+ System.out.println("Locked File");
+ TimeUnit.MILLISECONDS.sleep(100);
+ fl.release();
+ System.out.println("Released Lock");
+ }
+ fos.close();
+ }
+} /* Output:
+Locked File
+Released Lock
+*///:~
diff --git a/src/main/java/io/FileOutputShortcut.java b/src/main/java/io/FileOutputShortcut.java
new file mode 100755
index 0000000..81d080e
--- /dev/null
+++ b/src/main/java/io/FileOutputShortcut.java
@@ -0,0 +1,21 @@
+package io;//: io/FileOutputShortcut.java
+import java.io.*;
+
+public class FileOutputShortcut {
+ static String file = "FileOutputShortcut.out";
+ public static void main(String[] args)
+ throws IOException {
+ BufferedReader in = new BufferedReader(
+ new StringReader(
+ BufferedInputFile.read("FileOutputShortcut.java")));
+ // Here's the shortcut:
+ PrintWriter out = new PrintWriter(file);
+ int lineCount = 1;
+ String s;
+ while((s = in.readLine()) != null )
+ out.println(lineCount++ + ": " + s);
+ out.close();
+ // Show the stored file:
+ System.out.println(BufferedInputFile.read(file));
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/FormattedMemoryInput.java b/src/main/java/io/FormattedMemoryInput.java
new file mode 100755
index 0000000..530812a
--- /dev/null
+++ b/src/main/java/io/FormattedMemoryInput.java
@@ -0,0 +1,18 @@
+package io;//: io/FormattedMemoryInput.java
+import java.io.*;
+
+public class FormattedMemoryInput {
+ public static void main(String[] args)
+ throws IOException {
+ try {
+ DataInputStream in = new DataInputStream(
+ new ByteArrayInputStream(
+ BufferedInputFile.read(
+ "img/student.txt").getBytes()));
+ while(true)
+ System.out.print((char)in.readByte());
+ } catch(EOFException e) {
+ System.err.println("End of stream");
+ }
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/FreezeAlien.java b/src/main/java/io/FreezeAlien.java
new file mode 100755
index 0000000..e09dee6
--- /dev/null
+++ b/src/main/java/io/FreezeAlien.java
@@ -0,0 +1,12 @@
+package io;//: io/FreezeAlien.java
+// Create a serialized output file.
+import java.io.*;
+
+public class FreezeAlien {
+ public static void main(String[] args) throws Exception {
+ ObjectOutput out = new ObjectOutputStream(
+ new FileOutputStream("X.file"));
+ Alien quellek = new Alien();
+ out.writeObject(quellek);
+ }
+} ///:~
diff --git a/src/main/java/io/GZIPcompress.java b/src/main/java/io/GZIPcompress.java
new file mode 100755
index 0000000..cc7f770
--- /dev/null
+++ b/src/main/java/io/GZIPcompress.java
@@ -0,0 +1,35 @@
+package io;//: io/GZIPcompress.java
+// {Args: GZIPcompress.java}
+import java.util.zip.*;
+import java.io.*;
+
+public class GZIPcompress {
+ public static void main(String[] args)
+ throws IOException {
+ if(args.length == 0) {
+ System.out.println(
+ "Usage: \nGZIPcompress file\n" +
+ "\tUses GZIP compression to compress " +
+ "the file to test.gz");
+ System.exit(1);
+ }
+ BufferedReader in = new BufferedReader(
+ new FileReader(args[0]));
+ BufferedOutputStream out = new BufferedOutputStream(
+ new GZIPOutputStream(
+ new FileOutputStream("test.gz")));
+ System.out.println("Writing file");
+ int c;
+ while((c = in.read()) != -1)
+ out.write(c);
+ in.close();
+ out.close();
+ System.out.println("Reading file");
+ BufferedReader in2 = new BufferedReader(
+ new InputStreamReader(new GZIPInputStream(
+ new FileInputStream("test.gz"))));
+ String s;
+ while((s = in2.readLine()) != null)
+ System.out.println(s);
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/GetChannel.java b/src/main/java/io/GetChannel.java
new file mode 100755
index 0000000..19c1ca0
--- /dev/null
+++ b/src/main/java/io/GetChannel.java
@@ -0,0 +1,31 @@
+package io;//: io/GetChannel.java
+// Getting channels from streams
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class GetChannel {
+ private static final int BSIZE = 1024;
+ public static void main(String[] args) throws Exception {
+ // Write a file:
+ FileChannel fc =
+ new FileOutputStream("data.txt").getChannel();
+ fc.write(ByteBuffer.wrap("Some text ".getBytes()));
+ fc.close();
+ // Add to the end of the file:
+ fc =
+ new RandomAccessFile("data.txt", "rw").getChannel();
+ fc.position(fc.size()); // Move to the end
+ fc.write(ByteBuffer.wrap("Some more".getBytes()));
+ fc.close();
+ // Read the file:
+ fc = new FileInputStream("data.txt").getChannel();
+ ByteBuffer buff = ByteBuffer.allocate(BSIZE);
+ fc.read(buff);
+ buff.flip();
+ while(buff.hasRemaining())
+ System.out.print((char)buff.get());
+ }
+} /* Output:
+Some text Some more
+*///:~
diff --git a/src/main/java/io/GetData.java b/src/main/java/io/GetData.java
new file mode 100755
index 0000000..a1c6437
--- /dev/null
+++ b/src/main/java/io/GetData.java
@@ -0,0 +1,53 @@
+package io;//: io/GetData.java
+// Getting different representations from a ByteBuffer
+import java.nio.*;
+import static net.mindview.util.Print.*;
+
+public class GetData {
+ private static final int BSIZE = 1024;
+ public static void main(String[] args) {
+ ByteBuffer bb = ByteBuffer.allocate(BSIZE);
+ // Allocation automatically zeroes the ByteBuffer:
+ int i = 0;
+ while(i++ < bb.limit())
+ if(bb.get() != 0)
+ print("nonzero");
+ print("i = " + i);
+ bb.rewind();
+ // Store and read a char array:
+ bb.asCharBuffer().put("Howdy!");
+ char c;
+ while((c = bb.getChar()) != 0)
+ printnb(c + " ");
+ print();
+ bb.rewind();
+ // Store and read a short:
+ bb.asShortBuffer().put((short)471142);
+ print(bb.getShort());
+ bb.rewind();
+ // Store and read an int:
+ bb.asIntBuffer().put(99471142);
+ print(bb.getInt());
+ bb.rewind();
+ // Store and read a long:
+ bb.asLongBuffer().put(99471142);
+ print(bb.getLong());
+ bb.rewind();
+ // Store and read a float:
+ bb.asFloatBuffer().put(99471142);
+ print(bb.getFloat());
+ bb.rewind();
+ // Store and read a double:
+ bb.asDoubleBuffer().put(99471142);
+ print(bb.getDouble());
+ bb.rewind();
+ }
+} /* Output:
+i = 1025
+H o w d y !
+12390
+99471142
+99471142
+9.9471144E7
+9.9471142E7
+*///:~
diff --git a/src/main/java/io/IntBufferDemo.java b/src/main/java/io/IntBufferDemo.java
new file mode 100755
index 0000000..f95d5ea
--- /dev/null
+++ b/src/main/java/io/IntBufferDemo.java
@@ -0,0 +1,31 @@
+package io;//: io/IntBufferDemo.java
+// Manipulating ints in a ByteBuffer with an IntBuffer
+import java.nio.*;
+
+public class IntBufferDemo {
+ private static final int BSIZE = 1024;
+ public static void main(String[] args) {
+ ByteBuffer bb = ByteBuffer.allocate(BSIZE);
+ IntBuffer ib = bb.asIntBuffer();
+ // Store an array of int:
+ ib.put(new int[]{ 11, 42, 47, 99, 143, 811, 1016 });
+ // Absolute location read and write:
+ System.out.println(ib.get(3));
+ ib.put(3, 1811);
+ // Setting a new limit before rewinding the buffer.
+ ib.flip();
+ while(ib.hasRemaining()) {
+ int i = ib.get();
+ System.out.println(i);
+ }
+ }
+} /* Output:
+99
+11
+42
+47
+1811
+143
+811
+1016
+*///:~
diff --git a/src/main/java/io/LargeMappedFiles.java b/src/main/java/io/LargeMappedFiles.java
new file mode 100755
index 0000000..2b276bc
--- /dev/null
+++ b/src/main/java/io/LargeMappedFiles.java
@@ -0,0 +1,21 @@
+package io;//: io/LargeMappedFiles.java
+// Creating a very large file using mapping.
+// {RunByHand}
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+import static net.mindview.util.Print.*;
+
+public class LargeMappedFiles {
+ static int length = 0x8FFFFFF; // 128 MB
+ public static void main(String[] args) throws Exception {
+ MappedByteBuffer out =
+ new RandomAccessFile("test.dat", "rw").getChannel()
+ .map(FileChannel.MapMode.READ_WRITE, 0, length);
+ for(int i = 0; i < length; i++)
+ out.put((byte)'x');
+ print("Finished writing");
+ for(int i = length/2; i < length/2 + 6; i++)
+ printnb((char)out.get(i));
+ }
+} ///:~
diff --git a/src/main/java/io/LockingMappedFiles.java b/src/main/java/io/LockingMappedFiles.java
new file mode 100755
index 0000000..59a716e
--- /dev/null
+++ b/src/main/java/io/LockingMappedFiles.java
@@ -0,0 +1,47 @@
+package io;//: io/LockingMappedFiles.java
+// Locking portions of a mapped file.
+// {RunByHand}
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class LockingMappedFiles {
+ static final int LENGTH = 0x8FFFFFF; // 128 MB
+ static FileChannel fc;
+ public static void main(String[] args) throws Exception {
+ fc =
+ new RandomAccessFile("test.dat", "rw").getChannel();
+ MappedByteBuffer out =
+ fc.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
+ for(int i = 0; i < LENGTH; i++)
+ out.put((byte)'x');
+ new LockAndModify(out, 0, 0 + LENGTH/3);
+ new LockAndModify(out, LENGTH/2, LENGTH/2 + LENGTH/4);
+ }
+ private static class LockAndModify extends Thread {
+ private ByteBuffer buff;
+ private int start, end;
+ LockAndModify(ByteBuffer mbb, int start, int end) {
+ this.start = start;
+ this.end = end;
+ mbb.limit(end);
+ mbb.position(start);
+ buff = mbb.slice();
+ start();
+ }
+ public void run() {
+ try {
+ // Exclusive lock with no overlap:
+ FileLock fl = fc.lock(start, end, false);
+ System.out.println("Locked: "+ start +" to "+ end);
+ // Perform modification:
+ while(buff.position() < buff.limit() - 1)
+ buff.put((byte)(buff.get() + 1));
+ fl.release();
+ System.out.println("Released: "+start+" to "+ end);
+ } catch(IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+} ///:~
diff --git a/src/main/java/io/Logon.java b/src/main/java/io/Logon.java
new file mode 100755
index 0000000..234ffea
--- /dev/null
+++ b/src/main/java/io/Logon.java
@@ -0,0 +1,45 @@
+package io;//: io/Logon.java
+// Demonstrates the "transient" keyword.
+import java.util.concurrent.*;
+import java.io.*;
+import java.util.*;
+import static net.mindview.util.Print.*;
+
+public class Logon implements Serializable {
+ private Date date = new Date();
+ private String username;
+ private transient String password;
+ public Logon(String name, String pwd) {
+ username = name;
+ password = pwd;
+ }
+ public String toString() {
+ return "logon info: \n username: " + username +
+ "\n date: " + date + "\n password: " + password;
+ }
+ public static void main(String[] args) throws Exception {
+ Logon a = new Logon("Hulk", "myLittlePony");
+ print("logon a = " + a);
+ ObjectOutputStream o = new ObjectOutputStream(
+ new FileOutputStream("Logon.out"));
+ o.writeObject(a);
+ o.close();
+ TimeUnit.SECONDS.sleep(1); // Delay
+ // Now get them back:
+ ObjectInputStream in = new ObjectInputStream(
+ new FileInputStream("Logon.out"));
+ print("Recovering object at " + new Date());
+ a = (Logon)in.readObject();
+ print("logon a = " + a);
+ }
+} /* Output: (Sample)
+logon a = logon info:
+ username: Hulk
+ date: Sat Nov 19 15:03:26 MST 2005
+ password: myLittlePony
+Recovering object at Sat Nov 19 15:03:28 MST 2005
+logon a = logon info:
+ username: Hulk
+ date: Sat Nov 19 15:03:26 MST 2005
+ password: null
+*///:~
diff --git a/src/main/java/io/MakeDirectories.java b/src/main/java/io/MakeDirectories.java
new file mode 100755
index 0000000..33f14a9
--- /dev/null
+++ b/src/main/java/io/MakeDirectories.java
@@ -0,0 +1,81 @@
+package io;//: io/MakeDirectories.java
+// Demonstrates the use of 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: (80% match)
+created MakeDirectoriesTest
+Absolute path: d:\aaa-TIJ4\code\io\MakeDirectoriesTest
+ Can read: true
+ Can write: true
+ getName: MakeDirectoriesTest
+ getParent: null
+ getPath: MakeDirectoriesTest
+ length: 0
+ lastModified: 1101690308831
+It's a directory
+*///:~
diff --git a/src/main/java/io/MappedIO.java b/src/main/java/io/MappedIO.java
new file mode 100755
index 0000000..dae67be
--- /dev/null
+++ b/src/main/java/io/MappedIO.java
@@ -0,0 +1,108 @@
+package io;//: io/MappedIO.java
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class MappedIO {
+ private static int numOfInts = 4000000;
+ private static int numOfUbuffInts = 200000;
+ private abstract static class Tester {
+ private String name;
+ public Tester(String name) { this.name = name; }
+ public void runTest() {
+ System.out.print(name + ": ");
+ try {
+ long start = System.nanoTime();
+ test();
+ double duration = System.nanoTime() - start;
+ System.out.format("%.2f\n", duration/1.0e9);
+ } catch(IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ public abstract void test() throws IOException;
+ }
+ private static Tester[] tests = {
+ new Tester("Stream Write") {
+ public void test() throws IOException {
+ DataOutputStream dos = new DataOutputStream(
+ new BufferedOutputStream(
+ new FileOutputStream(new File("temp.tmp"))));
+ for(int i = 0; i < numOfInts; i++)
+ dos.writeInt(i);
+ dos.close();
+ }
+ },
+ new Tester("Mapped Write") {
+ public void test() throws IOException {
+ FileChannel fc =
+ new RandomAccessFile("temp.tmp", "rw")
+ .getChannel();
+ IntBuffer ib = fc.map(
+ FileChannel.MapMode.READ_WRITE, 0, fc.size())
+ .asIntBuffer();
+ for(int i = 0; i < numOfInts; i++)
+ ib.put(i);
+ fc.close();
+ }
+ },
+ new Tester("Stream Read") {
+ public void test() throws IOException {
+ DataInputStream dis = new DataInputStream(
+ new BufferedInputStream(
+ new FileInputStream("temp.tmp")));
+ for(int i = 0; i < numOfInts; i++)
+ dis.readInt();
+ dis.close();
+ }
+ },
+ new Tester("Mapped Read") {
+ public void test() throws IOException {
+ FileChannel fc = new FileInputStream(
+ new File("temp.tmp")).getChannel();
+ IntBuffer ib = fc.map(
+ FileChannel.MapMode.READ_ONLY, 0, fc.size())
+ .asIntBuffer();
+ while(ib.hasRemaining())
+ ib.get();
+ fc.close();
+ }
+ },
+ new Tester("Stream Read/Write") {
+ public void test() throws IOException {
+ RandomAccessFile raf = new RandomAccessFile(
+ new File("temp.tmp"), "rw");
+ raf.writeInt(1);
+ for(int i = 0; i < numOfUbuffInts; i++) {
+ raf.seek(raf.length() - 4);
+ raf.writeInt(raf.readInt());
+ }
+ raf.close();
+ }
+ },
+ new Tester("Mapped Read/Write") {
+ public void test() throws IOException {
+ FileChannel fc = new RandomAccessFile(
+ new File("temp.tmp"), "rw").getChannel();
+ IntBuffer ib = fc.map(
+ FileChannel.MapMode.READ_WRITE, 0, fc.size())
+ .asIntBuffer();
+ ib.put(0);
+ for(int i = 1; i < numOfUbuffInts; i++)
+ ib.put(ib.get(i - 1));
+ fc.close();
+ }
+ }
+ };
+ public static void main(String[] args) {
+ for(Tester test : tests)
+ test.runTest();
+ }
+} /* Output: (90% match)
+Stream Write: 0.56
+Mapped Write: 0.12
+Stream Read: 0.80
+Mapped Read: 0.07
+Stream Read/Write: 5.32
+Mapped Read/Write: 0.02
+*///:~
diff --git a/src/main/java/io/MemoryInput.java b/src/main/java/io/MemoryInput.java
new file mode 100755
index 0000000..ec5d52c
--- /dev/null
+++ b/src/main/java/io/MemoryInput.java
@@ -0,0 +1,13 @@
+package io;//: io/MemoryInput.java
+import java.io.*;
+
+public class MemoryInput {
+ public static void main(String[] args)
+ throws IOException {
+ StringReader in = new StringReader(
+ BufferedInputFile.read("MemoryInput.java"));
+ int c;
+ while((c = in.read()) != -1)
+ System.out.print((char)c);
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/MyWorld.java b/src/main/java/io/MyWorld.java
new file mode 100755
index 0000000..9925f65
--- /dev/null
+++ b/src/main/java/io/MyWorld.java
@@ -0,0 +1,70 @@
+package io;//: io/MyWorld.java
+import java.io.*;
+import java.util.*;
+import static net.mindview.util.Print.*;
+
+class House implements Serializable {}
+
+class Animal implements Serializable {
+ private String name;
+ private House preferredHouse;
+ Animal(String nm, House h) {
+ name = nm;
+ preferredHouse = h;
+ }
+ public String toString() {
+ return name + "[" + super.toString() +
+ "], " + preferredHouse + "\n";
+ }
+}
+
+public class MyWorld {
+ public static void main(String[] args)
+ throws IOException, ClassNotFoundException {
+ House house = new House();
+ List animals = new ArrayList();
+ animals.add(new Animal("Bosco the dog", house));
+ animals.add(new Animal("Ralph the hamster", house));
+ animals.add(new Animal("Molly the cat", house));
+ print("animals: " + animals);
+ ByteArrayOutputStream buf1 =
+ new ByteArrayOutputStream();
+ ObjectOutputStream o1 = new ObjectOutputStream(buf1);
+ o1.writeObject(animals);
+ o1.writeObject(animals); // Write a 2nd set
+ // Write to a different stream:
+ ByteArrayOutputStream buf2 =
+ new ByteArrayOutputStream();
+ ObjectOutputStream o2 = new ObjectOutputStream(buf2);
+ o2.writeObject(animals);
+ // Now get them back:
+ ObjectInputStream in1 = new ObjectInputStream(
+ new ByteArrayInputStream(buf1.toByteArray()));
+ ObjectInputStream in2 = new ObjectInputStream(
+ new ByteArrayInputStream(buf2.toByteArray()));
+ List
+ animals1 = (List)in1.readObject(),
+ animals2 = (List)in1.readObject(),
+ animals3 = (List)in2.readObject();
+ print("animals1: " + animals1);
+ print("animals2: " + animals2);
+ print("animals3: " + animals3);
+ }
+} /* Output: (Sample)
+animals: [Bosco the dog[Animal@addbf1], House@42e816
+, Ralph the hamster[Animal@9304b1], House@42e816
+, Molly the cat[Animal@190d11], House@42e816
+]
+animals1: [Bosco the dog[Animal@de6f34], House@156ee8e
+, Ralph the hamster[Animal@47b480], House@156ee8e
+, Molly the cat[Animal@19b49e6], House@156ee8e
+]
+animals2: [Bosco the dog[Animal@de6f34], House@156ee8e
+, Ralph the hamster[Animal@47b480], House@156ee8e
+, Molly the cat[Animal@19b49e6], House@156ee8e
+]
+animals3: [Bosco the dog[Animal@10d448], House@e0e1c6
+, Ralph the hamster[Animal@6ca1c], House@e0e1c6
+, Molly the cat[Animal@1bf216a], House@e0e1c6
+]
+*///:~
diff --git a/src/main/java/io/OSExecuteDemo.java b/src/main/java/io/OSExecuteDemo.java
new file mode 100755
index 0000000..bb33217
--- /dev/null
+++ b/src/main/java/io/OSExecuteDemo.java
@@ -0,0 +1,15 @@
+package io;//: io/OSExecuteDemo.java
+// Demonstrates standard I/O redirection.
+import net.mindview.util.*;
+
+public class OSExecuteDemo {
+ public static void main(String[] args) {
+ OSExecute.command("javap OSExecuteDemo");
+ }
+} /* Output:
+Compiled from "OSExecuteDemo.java"
+public class OSExecuteDemo extends java.lang.Object{
+ public OSExecuteDemo();
+ public static void main(java.lang.String[]);
+}
+*///:~
diff --git a/src/main/java/io/PreferencesDemo.java b/src/main/java/io/PreferencesDemo.java
new file mode 100755
index 0000000..ecb63a0
--- /dev/null
+++ b/src/main/java/io/PreferencesDemo.java
@@ -0,0 +1,29 @@
+package io;//: io/PreferencesDemo.java
+import java.util.prefs.*;
+import static net.mindview.util.Print.*;
+
+public class PreferencesDemo {
+ public static void main(String[] args) throws Exception {
+ Preferences prefs = Preferences
+ .userNodeForPackage(PreferencesDemo.class);
+ prefs.put("Location", "Oz");
+ prefs.put("Footwear", "Ruby Slippers");
+ prefs.putInt("Companions", 4);
+ prefs.putBoolean("Are there witches?", true);
+ int usageCount = prefs.getInt("UsageCount", 0);
+ usageCount++;
+ prefs.putInt("UsageCount", usageCount);
+ for(String key : prefs.keys())
+ print(key + ": "+ prefs.get(key, null));
+ // You must always provide a default value:
+ print("How many companions does Dorothy have? " +
+ prefs.getInt("Companions", 0));
+ }
+} /* Output: (Sample)
+Location: Oz
+Footwear: Ruby Slippers
+Companions: 4
+Are there witches?: true
+UsageCount: 53
+How many companions does Dorothy have? 4
+*///:~
diff --git a/src/main/java/io/RecoverCADState.java b/src/main/java/io/RecoverCADState.java
new file mode 100755
index 0000000..199bd57
--- /dev/null
+++ b/src/main/java/io/RecoverCADState.java
@@ -0,0 +1,31 @@
+package io;//: io/RecoverCADState.java
+// Restoring the state of the pretend CAD system.
+// {RunFirst: StoreCADState}
+import java.io.*;
+import java.util.*;
+
+public class RecoverCADState {
+ @SuppressWarnings("unchecked")
+ public static void main(String[] args) throws Exception {
+ ObjectInputStream in = new ObjectInputStream(
+ new FileInputStream("CADState.out"));
+ // Read in the same order they were written:
+ List> shapeTypes =
+ (List>)in.readObject();
+ Line.deserializeStaticState(in);
+ List shapes = (List)in.readObject();
+ System.out.println(shapes);
+ }
+} /* Output:
+[class Circlecolor[1] xPos[58] yPos[55] dim[93]
+, class Squarecolor[0] xPos[61] yPos[61] dim[29]
+, class Linecolor[3] xPos[68] yPos[0] dim[22]
+, class Circlecolor[1] xPos[7] yPos[88] dim[28]
+, class Squarecolor[0] xPos[51] yPos[89] dim[9]
+, class Linecolor[3] xPos[78] yPos[98] dim[61]
+, class Circlecolor[1] xPos[20] yPos[58] dim[16]
+, class Squarecolor[0] xPos[40] yPos[11] dim[22]
+, class Linecolor[3] xPos[4] yPos[83] dim[6]
+, class Circlecolor[1] xPos[75] yPos[10] dim[42]
+]
+*///:~
diff --git a/src/main/java/io/Redirecting.java b/src/main/java/io/Redirecting.java
new file mode 100755
index 0000000..06d4a99
--- /dev/null
+++ b/src/main/java/io/Redirecting.java
@@ -0,0 +1,25 @@
+package io;//: io/Redirecting.java
+// Demonstrates standard I/O redirection.
+import java.io.*;
+
+public class Redirecting {
+ public static void main(String[] args)
+ throws IOException {
+ PrintStream console = System.out;
+ BufferedInputStream in = new BufferedInputStream(
+ new FileInputStream("Redirecting.java"));
+ PrintStream out = new PrintStream(
+ new BufferedOutputStream(
+ new FileOutputStream("test.out")));
+ System.setIn(in);
+ System.setOut(out);
+ System.setErr(out);
+ BufferedReader br = new BufferedReader(
+ new InputStreamReader(System.in));
+ String s;
+ while((s = br.readLine()) != null)
+ System.out.println(s);
+ out.close(); // Remember this!
+ System.setOut(console);
+ }
+} ///:~
diff --git a/src/main/java/io/SerialCtl.java b/src/main/java/io/SerialCtl.java
new file mode 100755
index 0000000..a45149e
--- /dev/null
+++ b/src/main/java/io/SerialCtl.java
@@ -0,0 +1,44 @@
+package io;//: io/SerialCtl.java
+// Controlling serialization by adding your own
+// writeObject() and readObject() methods.
+import java.io.*;
+
+public class SerialCtl implements Serializable {
+ private String a;
+ private transient String b;
+ public SerialCtl(String aa, String bb) {
+ a = "Not Transient: " + aa;
+ b = "Transient: " + bb;
+ }
+ public String toString() { return a + "\n" + b; }
+ private void writeObject(ObjectOutputStream stream)
+ throws IOException {
+ stream.defaultWriteObject();
+ stream.writeObject(b);
+ }
+ private void readObject(ObjectInputStream stream)
+ throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+ b = (String)stream.readObject();
+ }
+ public static void main(String[] args)
+ throws IOException, ClassNotFoundException {
+ SerialCtl sc = new SerialCtl("Test1", "Test2");
+ System.out.println("Before:\n" + sc);
+ ByteArrayOutputStream buf= new ByteArrayOutputStream();
+ ObjectOutputStream o = new ObjectOutputStream(buf);
+ o.writeObject(sc);
+ // Now get it back:
+ ObjectInputStream in = new ObjectInputStream(
+ new ByteArrayInputStream(buf.toByteArray()));
+ SerialCtl sc2 = (SerialCtl)in.readObject();
+ System.out.println("After:\n" + sc2);
+ }
+} /* Output:
+Before:
+Not Transient: Test1
+Transient: Test2
+After:
+Not Transient: Test1
+Transient: Test2
+*///:~
diff --git a/src/main/java/io/StoreCADState.java b/src/main/java/io/StoreCADState.java
new file mode 100755
index 0000000..919f26a
--- /dev/null
+++ b/src/main/java/io/StoreCADState.java
@@ -0,0 +1,106 @@
+package io;//: io/StoreCADState.java
+// Saving the state of a pretend CAD system.
+import java.io.*;
+import java.util.*;
+
+abstract class Shape implements Serializable {
+ public static final int RED = 1, BLUE = 2, GREEN = 3;
+ private int xPos, yPos, dimension;
+ private static Random rand = new Random(47);
+ private static int counter = 0;
+ public abstract void setColor(int newColor);
+ public abstract int getColor();
+ public Shape(int xVal, int yVal, int dim) {
+ xPos = xVal;
+ yPos = yVal;
+ dimension = dim;
+ }
+ public String toString() {
+ return getClass() +
+ "color[" + getColor() + "] xPos[" + xPos +
+ "] yPos[" + yPos + "] dim[" + dimension + "]\n";
+ }
+ public static Shape randomFactory() {
+ int xVal = rand.nextInt(100);
+ int yVal = rand.nextInt(100);
+ int dim = rand.nextInt(100);
+ switch(counter++ % 3) {
+ default:
+ case 0: return new Circle(xVal, yVal, dim);
+ case 1: return new Square(xVal, yVal, dim);
+ case 2: return new Line(xVal, yVal, dim);
+ }
+ }
+}
+
+class Circle extends Shape {
+ private static int color = RED;
+ public Circle(int xVal, int yVal, int dim) {
+ super(xVal, yVal, dim);
+ }
+ public void setColor(int newColor) { color = newColor; }
+ public int getColor() { return color; }
+}
+
+class Square extends Shape {
+ private static int color;
+ public Square(int xVal, int yVal, int dim) {
+ super(xVal, yVal, dim);
+ color = RED;
+ }
+ public void setColor(int newColor) { color = newColor; }
+ public int getColor() { return color; }
+}
+
+class Line extends Shape {
+ private static int color = RED;
+ public static void
+ serializeStaticState(ObjectOutputStream os)
+ throws IOException { os.writeInt(color); }
+ public static void
+ deserializeStaticState(ObjectInputStream os)
+ throws IOException { color = os.readInt(); }
+ public Line(int xVal, int yVal, int dim) {
+ super(xVal, yVal, dim);
+ }
+ public void setColor(int newColor) { color = newColor; }
+ public int getColor() { return color; }
+}
+
+public class StoreCADState {
+ public static void main(String[] args) throws Exception {
+ List> shapeTypes =
+ new ArrayList>();
+ // Add references to the class objects:
+ shapeTypes.add(Circle.class);
+ shapeTypes.add(Square.class);
+ shapeTypes.add(Line.class);
+ List shapes = new ArrayList();
+ // Make some shapes:
+ for(int i = 0; i < 10; i++)
+ shapes.add(Shape.randomFactory());
+ // Set all the static colors to GREEN:
+ for(int i = 0; i < 10; i++)
+ ((Shape)shapes.get(i)).setColor(Shape.GREEN);
+ // Save the state vector:
+ ObjectOutputStream out = new ObjectOutputStream(
+ new FileOutputStream("CADState.out"));
+ out.writeObject(shapeTypes);
+ Line.serializeStaticState(out);
+ out.writeObject(shapes);
+ // Display the shapes:
+ System.out.println(shapes);
+ }
+} /* Output:
+[class Circlecolor[3] xPos[58] yPos[55] dim[93]
+, class Squarecolor[3] xPos[61] yPos[61] dim[29]
+, class Linecolor[3] xPos[68] yPos[0] dim[22]
+, class Circlecolor[3] xPos[7] yPos[88] dim[28]
+, class Squarecolor[3] xPos[51] yPos[89] dim[9]
+, class Linecolor[3] xPos[78] yPos[98] dim[61]
+, class Circlecolor[3] xPos[20] yPos[58] dim[16]
+, class Squarecolor[3] xPos[40] yPos[11] dim[22]
+, class Linecolor[3] xPos[4] yPos[83] dim[6]
+, class Circlecolor[3] xPos[75] yPos[10] dim[42]
+]
+*///:~
diff --git a/src/main/java/io/StoringAndRecoveringData.java b/src/main/java/io/StoringAndRecoveringData.java
new file mode 100755
index 0000000..c68a63e
--- /dev/null
+++ b/src/main/java/io/StoringAndRecoveringData.java
@@ -0,0 +1,30 @@
+package io;//: io/StoringAndRecoveringData.java
+import java.io.*;
+
+public class StoringAndRecoveringData {
+ public static void main(String[] args)
+ throws IOException {
+ DataOutputStream out = new DataOutputStream(
+ new BufferedOutputStream(
+ new FileOutputStream("Data.txt")));
+ out.writeDouble(3.14159);
+ out.writeUTF("That was pi");
+ out.writeDouble(1.41413);
+ out.writeUTF("Square root of 2");
+ out.close();
+ DataInputStream in = new DataInputStream(
+ new BufferedInputStream(
+ new FileInputStream("Data.txt")));
+ System.out.println(in.readDouble());
+ // Only readUTF() will recover the
+ // Java-UTF String properly:
+ System.out.println(in.readUTF());
+ System.out.println(in.readDouble());
+ System.out.println(in.readUTF());
+ }
+} /* Output:
+3.14159
+That was pi
+1.41413
+Square root of 2
+*///:~
diff --git a/src/main/java/io/StreamToken.java b/src/main/java/io/StreamToken.java
index 025f961..dd931b4 100644
--- a/src/main/java/io/StreamToken.java
+++ b/src/main/java/io/StreamToken.java
@@ -34,8 +34,8 @@ public static long statis(String fileName) {
try {
fileReader = new FileReader(fileName);
//创建分析给定字符流的标记生成器
- StreamTokenizer st = new StreamTokenizer(new BufferedReader(
- fileReader));
+ StreamTokenizer st = new StreamTokenizer(
+ fileReader);
//ordinaryChar方法指定字符参数在此标记生成器中是“普通”字符。
//下面指定单引号、双引号和注释符号是普通字符
diff --git a/src/main/java/io/TestEOF.java b/src/main/java/io/TestEOF.java
new file mode 100755
index 0000000..8d0d4c6
--- /dev/null
+++ b/src/main/java/io/TestEOF.java
@@ -0,0 +1,14 @@
+package io;//: io/TestEOF.java
+// Testing for end of file while reading a byte at a time.
+import java.io.*;
+
+public class TestEOF {
+ public static void main(String[] args)
+ throws IOException {
+ DataInputStream in = new DataInputStream(
+ new BufferedInputStream(
+ new FileInputStream("TestEOF.java")));
+ while(in.available() != 0)
+ System.out.print((char)in.readByte());
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/TransferTo.java b/src/main/java/io/TransferTo.java
new file mode 100755
index 0000000..9e3a40c
--- /dev/null
+++ b/src/main/java/io/TransferTo.java
@@ -0,0 +1,20 @@
+package io;//: io/TransferTo.java
+// Using transferTo() between channels
+// {Args: TransferTo.java TransferTo.txt}
+import java.nio.channels.*;
+import java.io.*;
+
+public class TransferTo {
+ public static void main(String[] args) throws Exception {
+ if(args.length != 2) {
+ System.out.println("arguments: sourcefile destfile");
+ System.exit(1);
+ }
+ FileChannel
+ in = new FileInputStream(args[0]).getChannel(),
+ out = new FileOutputStream(args[1]).getChannel();
+ in.transferTo(0, in.size(), out);
+ // Or:
+ // out.transferFrom(in, 0, in.size());
+ }
+} ///:~
diff --git a/src/main/java/io/UsingBuffers.java b/src/main/java/io/UsingBuffers.java
new file mode 100755
index 0000000..af9da28
--- /dev/null
+++ b/src/main/java/io/UsingBuffers.java
@@ -0,0 +1,30 @@
+package io;//: io/UsingBuffers.java
+import java.nio.*;
+import static net.mindview.util.Print.*;
+
+public class UsingBuffers {
+ private static void symmetricScramble(CharBuffer buffer){
+ while(buffer.hasRemaining()) {
+ buffer.mark();
+ char c1 = buffer.get();
+ char c2 = buffer.get();
+ buffer.reset();
+ buffer.put(c2).put(c1);
+ }
+ }
+ public static void main(String[] args) {
+ char[] data = "UsingBuffers".toCharArray();
+ ByteBuffer bb = ByteBuffer.allocate(data.length * 2);
+ CharBuffer cb = bb.asCharBuffer();
+ cb.put(data);
+ print(cb.rewind());
+ symmetricScramble(cb);
+ print(cb.rewind());
+ symmetricScramble(cb);
+ print(cb.rewind());
+ }
+} /* Output:
+UsingBuffers
+sUniBgfuefsr
+UsingBuffers
+*///:~
diff --git a/src/main/java/io/UsingRandomAccessFile.java b/src/main/java/io/UsingRandomAccessFile.java
new file mode 100755
index 0000000..2966808
--- /dev/null
+++ b/src/main/java/io/UsingRandomAccessFile.java
@@ -0,0 +1,45 @@
+package io;//: io/UsingRandomAccessFile.java
+import java.io.*;
+
+public class UsingRandomAccessFile {
+ static String file = "rtest.dat";
+ static void display() throws IOException {
+ RandomAccessFile rf = new RandomAccessFile(file, "r");
+ for(int i = 0; i < 7; i++)
+ System.out.println(
+ "Value " + i + ": " + rf.readDouble());
+ System.out.println(rf.readUTF());
+ rf.close();
+ }
+ public static void main(String[] args)
+ throws IOException {
+ RandomAccessFile rf = new RandomAccessFile(file, "rw");
+ for(int i = 0; i < 7; i++)
+ rf.writeDouble(i*1.414);
+ rf.writeUTF("The end of the file");
+ rf.close();
+ display();
+ rf = new RandomAccessFile(file, "rw");
+ rf.seek(5*8);
+ rf.writeDouble(47.0001);
+ rf.close();
+ display();
+ }
+} /* Output:
+Value 0: 0.0
+Value 1: 1.414
+Value 2: 2.828
+Value 3: 4.242
+Value 4: 5.656
+Value 5: 7.069999999999999
+Value 6: 8.484
+The end of the file
+Value 0: 0.0
+Value 1: 1.414
+Value 2: 2.828
+Value 3: 4.242
+Value 4: 5.656
+Value 5: 47.0001
+Value 6: 8.484
+The end of the file
+*///:~
diff --git a/src/main/java/io/ViewBuffers.java b/src/main/java/io/ViewBuffers.java
new file mode 100755
index 0000000..e7c5abd
--- /dev/null
+++ b/src/main/java/io/ViewBuffers.java
@@ -0,0 +1,58 @@
+package io;//: io/ViewBuffers.java
+import java.nio.*;
+import static net.mindview.util.Print.*;
+
+public class ViewBuffers {
+ public static void main(String[] args) {
+ ByteBuffer bb = ByteBuffer.wrap(
+ new byte[]{ 0, 0, 0, 0, 0, 0, 0, 'a' });
+ bb.rewind();
+ printnb("Byte Buffer ");
+ while(bb.hasRemaining())
+ printnb(bb.position()+ " -> " + bb.get() + ", ");
+ print();
+ CharBuffer cb =
+ ((ByteBuffer)bb.rewind()).asCharBuffer();
+ printnb("Char Buffer ");
+ while(cb.hasRemaining())
+ printnb(cb.position() + " -> " + cb.get() + ", ");
+ print();
+ FloatBuffer fb =
+ ((ByteBuffer)bb.rewind()).asFloatBuffer();
+ printnb("Float Buffer ");
+ while(fb.hasRemaining())
+ printnb(fb.position()+ " -> " + fb.get() + ", ");
+ print();
+ IntBuffer ib =
+ ((ByteBuffer)bb.rewind()).asIntBuffer();
+ printnb("Int Buffer ");
+ while(ib.hasRemaining())
+ printnb(ib.position()+ " -> " + ib.get() + ", ");
+ print();
+ LongBuffer lb =
+ ((ByteBuffer)bb.rewind()).asLongBuffer();
+ printnb("Long Buffer ");
+ while(lb.hasRemaining())
+ printnb(lb.position()+ " -> " + lb.get() + ", ");
+ print();
+ ShortBuffer sb =
+ ((ByteBuffer)bb.rewind()).asShortBuffer();
+ printnb("Short Buffer ");
+ while(sb.hasRemaining())
+ printnb(sb.position()+ " -> " + sb.get() + ", ");
+ print();
+ DoubleBuffer db =
+ ((ByteBuffer)bb.rewind()).asDoubleBuffer();
+ printnb("Double Buffer ");
+ while(db.hasRemaining())
+ printnb(db.position()+ " -> " + db.get() + ", ");
+ }
+} /* Output:
+Byte Buffer 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, 6 -> 0, 7 -> 97,
+Char Buffer 0 -> , 1 -> , 2 -> , 3 -> a,
+Float Buffer 0 -> 0.0, 1 -> 1.36E-43,
+Int Buffer 0 -> 0, 1 -> 97,
+Long Buffer 0 -> 97,
+Short Buffer 0 -> 0, 1 -> 0, 2 -> 0, 3 -> 97,
+Double Buffer 0 -> 4.8E-322,
+*///:~
diff --git a/src/main/java/io/Worm.java b/src/main/java/io/Worm.java
new file mode 100755
index 0000000..2859b18
--- /dev/null
+++ b/src/main/java/io/Worm.java
@@ -0,0 +1,81 @@
+package io;//: io/Worm.java
+// Demonstrates object serialization.
+import java.io.*;
+import java.util.*;
+import static net.mindview.util.Print.*;
+
+class Data implements Serializable {
+ private int n;
+ public Data(int n) { this.n = n; }
+ public String toString() { return Integer.toString(n); }
+}
+
+public class Worm implements Serializable {
+ private static Random rand = new Random(47);
+ private Data[] d = {
+ new Data(rand.nextInt(10)),
+ new Data(rand.nextInt(10)),
+ new Data(rand.nextInt(10))
+ };
+ private Worm next;
+ private char c;
+ // Value of i == number of segments
+ public Worm(int i, char x) {
+ print("Worm constructor: " + i);
+ c = x;
+ if(--i > 0)
+ next = new Worm(i, (char)(x + 1));
+ }
+ public Worm() {
+ print("Default constructor");
+ }
+ public String toString() {
+ StringBuilder result = new StringBuilder(":");
+ result.append(c);
+ result.append("(");
+ for(Data dat : d)
+ result.append(dat);
+ result.append(")");
+ if(next != null)
+ result.append(next);
+ return result.toString();
+ }
+ public static void main(String[] args)
+ throws ClassNotFoundException, IOException {
+ Worm w = new Worm(6, 'a');
+ print("w = " + w);
+ ObjectOutputStream out = new ObjectOutputStream(
+ new FileOutputStream("worm.out"));
+ out.writeObject("Worm storage\n");
+ out.writeObject(w);
+ out.close(); // Also flushes output
+ ObjectInputStream in = new ObjectInputStream(
+ new FileInputStream("worm.out"));
+ String s = (String)in.readObject();
+ Worm w2 = (Worm)in.readObject();
+ print(s + "w2 = " + w2);
+ ByteArrayOutputStream bout =
+ new ByteArrayOutputStream();
+ ObjectOutputStream out2 = new ObjectOutputStream(bout);
+ out2.writeObject("Worm storage\n");
+ out2.writeObject(w);
+ out2.flush();
+ ObjectInputStream in2 = new ObjectInputStream(
+ new ByteArrayInputStream(bout.toByteArray()));
+ s = (String)in2.readObject();
+ Worm w3 = (Worm)in2.readObject();
+ print(s + "w3 = " + w3);
+ }
+} /* Output:
+Worm constructor: 6
+Worm constructor: 5
+Worm constructor: 4
+Worm constructor: 3
+Worm constructor: 2
+Worm constructor: 1
+w = :a(853):b(119):c(802):d(788):e(199):f(881)
+Worm storage
+w2 = :a(853):b(119):c(802):d(788):e(199):f(881)
+Worm storage
+w3 = :a(853):b(119):c(802):d(788):e(199):f(881)
+*///:~
diff --git a/src/main/java/io/ZipCompress.java b/src/main/java/io/ZipCompress.java
new file mode 100755
index 0000000..63e1dc8
--- /dev/null
+++ b/src/main/java/io/ZipCompress.java
@@ -0,0 +1,62 @@
+package io;//: io/ZipCompress.java
+// Uses Zip compression to compress any
+// number of files given on the command line.
+// {Args: ZipCompress.java}
+import java.util.zip.*;
+import java.io.*;
+import java.util.*;
+import static net.mindview.util.Print.*;
+
+public class ZipCompress {
+ public static void main(String[] args)
+ throws IOException {
+ FileOutputStream f = new FileOutputStream("test.zip");
+ CheckedOutputStream csum =
+ new CheckedOutputStream(f, new Adler32());
+ ZipOutputStream zos = new ZipOutputStream(csum);
+ BufferedOutputStream out =
+ new BufferedOutputStream(zos);
+ zos.setComment("A test of Java Zipping");
+ // No corresponding getComment(), though.
+ for(String arg : args) {
+ print("Writing file " + arg);
+ BufferedReader in =
+ new BufferedReader(new FileReader(arg));
+ zos.putNextEntry(new ZipEntry(arg));
+ int c;
+ while((c = in.read()) != -1)
+ out.write(c);
+ in.close();
+ out.flush();
+ }
+ out.close();
+ // Checksum valid only after the file has been closed!
+ print("Checksum: " + csum.getChecksum().getValue());
+ // Now extract the files:
+ print("Reading file");
+ FileInputStream fi = new FileInputStream("test.zip");
+ CheckedInputStream csumi =
+ new CheckedInputStream(fi, new Adler32());
+ ZipInputStream in2 = new ZipInputStream(csumi);
+ BufferedInputStream bis = new BufferedInputStream(in2);
+ ZipEntry ze;
+ while((ze = in2.getNextEntry()) != null) {
+ print("Reading file " + ze);
+ int x;
+ while((x = bis.read()) != -1)
+ System.out.write(x);
+ }
+ if(args.length == 1)
+ print("Checksum: " + csumi.getChecksum().getValue());
+ bis.close();
+ // Alternative way to open and read Zip files:
+ ZipFile zf = new ZipFile("test.zip");
+ Enumeration e = zf.entries();
+ while(e.hasMoreElements()) {
+ ZipEntry ze2 = (ZipEntry)e.nextElement();
+ print("File: " + ze2);
+ // ... and extract the data as before
+ }
+ /* if(args.length == 1) */
+ }
+} /* (Execute to see output) *///:~
diff --git a/src/main/java/io/build.xml b/src/main/java/io/build.xml
new file mode 100755
index 0000000..fe1ac48
--- /dev/null
+++ b/src/main/java/io/build.xml
@@ -0,0 +1,529 @@
+
+
+
+
+
+ build.xml for the source code for the io chapter of
+ Thinking in Java, 4th Edition by Bruce Eckel
+ Source code available at http://www.MindView.net
+ See copyright notice in CopyRight.txt
+
+ Ant available from: http://jakarta.apache.org/ant
+
+ To see options, type: ant -p
+
+ This file was automatically generated by AntBuilder
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/io/xfiles/ThawAlien.java b/src/main/java/io/xfiles/ThawAlien.java
new file mode 100755
index 0000000..11ef3b1
--- /dev/null
+++ b/src/main/java/io/xfiles/ThawAlien.java
@@ -0,0 +1,16 @@
+package io.xfiles;//: io/xfiles/ThawAlien.java
+// Try to recover a serialized file without the
+// class of object that's stored in that file.
+// {RunByHand}
+import java.io.*;
+
+public class ThawAlien {
+ public static void main(String[] args) throws Exception {
+ ObjectInputStream in = new ObjectInputStream(
+ new FileInputStream(new File("..", "X.file")));
+ Object mystery = in.readObject();
+ System.out.println(mystery.getClass());
+ }
+} /* Output:
+class Alien
+*///:~
diff --git a/src/main/java/leetcode/AddTwoNumber.java b/src/main/java/leetcode/AddTwoNumber.java
new file mode 100644
index 0000000..f14aee8
--- /dev/null
+++ b/src/main/java/leetcode/AddTwoNumber.java
@@ -0,0 +1,48 @@
+package leetcode;
+
+/**
+ * Created by helmeter on 6/11/16.
+ */
+public class AddTwoNumber {
+ // Definition for singly-linked list.
+ public static class ListNode {
+ int val;
+ ListNode next;
+ ListNode(int x) {
+ val = x;
+ next = null;
+ }
+ }
+
+ public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
+ ListNode ret = new ListNode(0);
+ ListNode cur = ret;
+
+ int sum = 0;
+ while (true) {
+ if (l1 != null) {
+ sum += l1.val;
+ l1 = l1.next;
+ }
+ if (l2 != null) {
+ sum += l2.val;
+ l2 = l2.next;
+ }
+ cur.val = sum % 10;
+ sum /= 10;
+ if (l1 != null || l2 != null || sum != 0) {
+ cur = (cur.next = new ListNode(0));
+ } else {
+ break;
+ }
+ }
+ return ret;
+ }
+
+ public static void main(String[] args) {
+
+ AddTwoNumber s = new AddTwoNumber();
+
+ System.out.println("Not test case");
+ }
+}
diff --git a/src/main/java/leetcode/LongestSubString.java b/src/main/java/leetcode/LongestSubString.java
new file mode 100644
index 0000000..7a8a5d8
--- /dev/null
+++ b/src/main/java/leetcode/LongestSubString.java
@@ -0,0 +1,31 @@
+package leetcode;
+
+/**
+ * Created by helmeter on 6/11/16.
+ */
+public class LongestSubString {
+ public int lengthOfLongestSubstring(String s) {
+ int res = 0, left = 0;
+ int prev[] = new int[300];
+
+ // init prev array
+ for (int i = 0; i < 300; ++i)
+ prev[i] = -1;
+
+ for (int i = 0; i < s.length(); ++i) {
+ if (prev[s.charAt(i)] >= left)
+ left = prev[s.charAt(i)] + 1;
+ prev[s.charAt(i)] = i;
+ if (res < i - left + 1)
+ res = i - left + 1;
+ }
+ return res;
+ }
+
+ public static void main(String[] args) {
+
+ LongestSubString s = new LongestSubString();
+ System.out.println(s.lengthOfLongestSubstring("abca"));
+ }
+
+}
diff --git a/src/main/java/leetcode/Patent.java b/src/main/java/leetcode/Patent.java
new file mode 100644
index 0000000..dd06555
--- /dev/null
+++ b/src/main/java/leetcode/Patent.java
@@ -0,0 +1,30 @@
+package leetcode;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by helmeter on 6/13/16.
+ */
+public class Patent {
+ public List generateParenthesis(int n) {
+ List ans = new ArrayList();
+ dfs(ans, "", n, 0, 0);
+ return ans;
+ }
+
+ private void dfs(List ans, String curr, int n, int numl, int numr) {
+ if (numl == n && numr == n) {
+ ans.add(curr);
+ return;
+ }
+ if (numl < n)
+ dfs(ans, curr+'(', n, numl+1, numr);
+ if (numr < numl)
+ dfs(ans, curr+')', n, numl, numr+1);
+ }
+
+ public static void main(String[] args) {
+ System.out.println(new Patent().generateParenthesis(3));
+ }
+}
diff --git a/src/main/java/leetcode/PhoneNumber.java b/src/main/java/leetcode/PhoneNumber.java
new file mode 100644
index 0000000..c932e76
--- /dev/null
+++ b/src/main/java/leetcode/PhoneNumber.java
@@ -0,0 +1,46 @@
+package leetcode;
+
+/**
+ * Created by helmeter on 6/13/16.
+ */
+
+import java.util.ArrayList;
+ import java.util.List;
+ import java.util.Scanner;
+
+public class PhoneNumber {
+ private String[] alpha = new String[] {
+ " ",
+ "1", "abc", "def",
+ "ghi", "jkl", "mno",
+ "pqrs", "tuv", "wxyz"
+ };
+ private StringBuilder word;
+
+ private void dfs(List res, String digits, int cur) {
+ if (cur >= digits.length()) {
+ res.add(word.toString());
+ } else {
+ for (int i = 0; i < alpha[digits.charAt(cur) - '0'].length(); ++i) {
+ word.append(alpha[digits.charAt(cur) - '0'].charAt(i));
+ dfs(res, digits, cur + 1);
+ word.deleteCharAt(word.length() - 1);
+ }
+ }
+ }
+
+ public List letterCombinations(String digits) {
+ List ret = new ArrayList();
+ word = new StringBuilder();
+ dfs(ret, digits, 0);
+ return ret;
+ }
+
+ // debug
+ public static void main(String[] args) {
+
+ PhoneNumber s = new PhoneNumber();
+ int[] input = {1, 2, 3, 1};
+ System.out.println(s.letterCombinations("235"));
+ }
+}
diff --git a/src/main/java/leetcode/PhoneNumber2.java b/src/main/java/leetcode/PhoneNumber2.java
new file mode 100644
index 0000000..b5f23fa
--- /dev/null
+++ b/src/main/java/leetcode/PhoneNumber2.java
@@ -0,0 +1,40 @@
+package leetcode;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Created by helmeter on 6/13/16.
+ */
+public class PhoneNumber2 {
+ public List letterCombinations(String digits) {
+ Map map = new HashMap(){{
+ put('2', "abc"); put('3', "def"); put('4', "ghi"); put('5', "jkl");
+ put('6', "mno"); put('7', "pqrs"); put('8', "tuv"); put('9', "wxyz");
+ }};
+ List ret = new ArrayList();
+ if (digits.equals("")) {
+ return ret;
+ }
+ dfs(digits, 0, "", map, ret);
+ return ret;
+ }
+
+ private void dfs(String digits, int idx, String path, Map map, List ret) {
+ if (digits.length() == path.length()) {
+ ret.add(path);
+ return;
+ }
+ for (int i = idx; i < digits.length(); i++) {
+ for (char c: map.get(digits.charAt(i)).toCharArray()) {
+ dfs(digits, i+1, path+c, map, ret);
+ }
+ }
+ }
+
+ public static void main(String[] args) {
+ System.out.println(new PhoneNumber2().letterCombinations("237"));
+ }
+}
diff --git a/src/main/java/leetcode/TwoSum.java b/src/main/java/leetcode/TwoSum.java
new file mode 100644
index 0000000..4d93e6a
--- /dev/null
+++ b/src/main/java/leetcode/TwoSum.java
@@ -0,0 +1,40 @@
+package leetcode;
+
+import java.util.HashMap;
+import java.util.Scanner;
+
+/**
+ * Created by helmeter on 6/11/16.
+ */
+public class TwoSum {
+
+ public static int[] twoSum(int[] numbers, int target) {
+ int[] res = new int[2];
+ HashMap nums = new HashMap();
+
+ for (int i = 0; i < numbers.length; ++i) {
+ // add i-th number
+ Integer a = nums.get(numbers[i]);
+ if (a == null)
+ nums.put(numbers[i], i);
+
+ // find (target - numbers[i])
+ a = nums.get(target - numbers[i]);
+ if (a != null && a < i) {
+ res[0] = a + 1;
+ res[1] = i + 1;
+ break;
+ }
+ }
+ return res;
+ }
+
+ public static void main(String[] args) {
+
+ int[] numbers ={2,12,3,5,2,3};
+
+ int target = 4;
+ int[] res = twoSum(numbers, target);
+ System.out.println(res[0] + " " + res[1]);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/leetcode/media.java b/src/main/java/leetcode/media.java
new file mode 100644
index 0000000..41c5874
--- /dev/null
+++ b/src/main/java/leetcode/media.java
@@ -0,0 +1,51 @@
+package leetcode;
+
+/**
+ * Created by helmeter on 6/12/16.
+ */
+public class media {
+ public double findMedianSortedArrays(int A[], int B[]) {
+ int Alen = A.length;
+ int Blen = B.length;
+ int mid = (Alen + Blen) / 2;
+ // odd and even
+ if ((Alen + Blen) % 2 == 0) {
+ return (findKth(A, B, mid - 1, 0, Alen - 1, 0, Blen - 1) + findKth(A, B, mid, 0, Alen - 1, 0, Blen - 1)) / 2;
+ } else {
+ return findKth(A, B, mid, 0, Alen - 1, 0, Blen - 1);
+ }
+ }
+ public static double findKth(int[] a, int[] b, int k, int astart, int aend, int bstart, int bend) {
+ int alength = aend - astart + 1;
+ int blength = bend - astart + 1;
+ // special case
+ if (alength == 0)
+ return b[bstart + k];
+ if (blength == 0)
+ return a[astart + k];
+ if (k == 0)
+ return a[astart] < b[bstart] ? a[astart] : b[bstart];
+ // the number before mid
+ int amid = alength * k / (alength + blength);
+ int bmid = k - amid-1;
+ // the mid index
+ amid = amid + astart;
+ bmid = bmid + bstart;
+ if (a[amid] > b[bmid]) {
+ k = k - (bmid - bstart + 1);
+ aend = amid;
+ bstart = bmid + 1;
+ } else {
+ k = k - (amid - astart + 1);
+ bend = bmid;
+ astart = amid + 1;
+ }
+ return findKth(a, b, k, astart, aend, bstart, bend);
+ }
+
+ public static void main(String[] args) {
+ int[] a = {2,3,4,5,6,7};
+ int b[] = {3,5,6,7,8,9};
+ new media().findMedianSortedArrays(a,b);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/leetcode/removeElemet.java b/src/main/java/leetcode/removeElemet.java
new file mode 100644
index 0000000..01a9920
--- /dev/null
+++ b/src/main/java/leetcode/removeElemet.java
@@ -0,0 +1,30 @@
+package leetcode;
+
+import java.util.Arrays;
+import java.util.Comparator;
+
+/**
+ * Created by helmeter on 6/8/16.
+ */
+public class removeElemet {
+
+ public static int removeElement(int[] nums, int val) {
+ for(int i = 0;i