Java II Core [A]
Java Core
Java Core 1: Collection & Generics
- Collection: Subinterfaces: {BeanContext, BeanContextServices, BlockingDeque, BlockingQueue, Deque, List, NavigableSet, Queue, Set, SortedSet, TransferQueue }Classes: {AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedDeque, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector }
- Collection: clear(), isEmpty(), iterator(), toArray()
- ThreadSafe: ConcurrentHashMap,IdentityHashMap , SynchronizedHashMap,Vector, HashTable, CopyOnWriteArrayList,CopyOnWriteArraySet, Stack, ConcurrentLinkedQueue, BlockingQueue
- ThreadSafe: List syncList = Collections.synchronizedList(new ArrayList());
- Queue: FIFO
- Stack: LIFO
- List: Classes {AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector }
- List: Repetition allowed, ordered
if(list != null && list.size()>0){ //list is not null}
- ArrayList Size changeable: Search, Traversal
- ArrayList: boolean add(Object o), void add(int index, Object o), int size(), object get(int index), boolean contains(Object o), boolean remove(Object o), object remove(int index)
import java.util.ArrayList;
public class TestArrayList {
public static void main(String[] args) {
//create ArrayList
ArrayList alist= new ArrayList();
alist.add(12);
alist.add("TEN");
alist.add(22.0);
System.out.println("alist size: "+alist.size());
System.out.println("second element is: "+alist.get(1));
for(int i=0; i<alist.size(); i++){
System.out.println(alist.get(i));
}
System.out.println("___________________");
alist.add(3,23);
for(Object o: alist){
System.out.println(o);
}
if(alist.contains("TEN")){
alist.remove("TEN");
alist.remove((Object)12);
}
System.out.println("___________________");
alist.add(0,23);
for(Object o: alist){
System.out.println(o);
}
System.out.println(alist.indexOf(22));
System.out.println(alist.indexOf(22.0));
alist.clone();
System.out.println("alist : "+alist.toString());
System.out.println("alist clone: "+alist.clone().toString());
alist.clear();
System.out.println("alist : "+alist.toString());
}
}
- LinkedList: Interfaces: Serializable, Cloneable, Iterable, Collection, Deque, List, Queue
- LinkedList Add, Remove
- LinkedList: void addFirst(Object o), void addLast(Object o), Object getFirst(), Object getLast(), Object removeFirst(), Object removeLast() …poll…peek…
import java.util.LinkedList;
public class TestLinkedList {
public static void main(String[] args) {
LinkedList llist= new LinkedList();
llist.add("first");
llist.addFirst("prefirst");
llist.add("second");
System.out.println(llist.getFirst());
System.out.println("list____");
llist.removeFirst();
for(Object o: llist){
System.out.println(o);
}
}
}
- Set: Subinterfaces: {NavigableSet, SortedSet} Classes {AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet }
- Set: One copy per type, no order
- HashSet: boolean add(E e), clear(), clone(), contains(Object o), isEmpty(), iterator(), remove(Object o), size();
import java.util.HashSet;
import java.util.Iterator;
public class TestHashSet {
public static void main(String[] args) {
HashSet hset= new HashSet();
hset.add("Today");
hset.add("Tomorrow");
hset.add("Sun");
hset.add(null);
hset.add("Moon");
hset.add("Sun");
System.out.println(hset.size());
for(Object h: hset){
System.out.println(h);
}
System.out.println("Hashset___");
//use iterator
Iterator it=hset.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Dog {
private String name;
private String type;
public Dog() {}
public Dog(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
class TestHashSetDog{
public static void main(String[] args) {
Set dogs= new HashSet();
Dog d1= new Dog("Dog1","German Shepherd");
Dog d2= new Dog("Dog2","Golden Retriever");
Dog d3= new Dog("Dog3","Poodle");
Dog d4= new Dog("Dog4","Chihuahua");
dogs.add(d1);
dogs.add(d2);
dogs.add(d3);
dogs.add(d4);
Iterator it=dogs.iterator();
while(it.hasNext()){// not sequential
Dog d=(Dog)it.next();
System.out.println(d.getName()+" "+d.getType());
}
}
}
- TreeSet is a SortedSet: has sequential properties
- TreeSet: Interfaces: {Serializable, Cloneable, Iterable, Collection, NavigableSet, Set, SortedSet}
- implement Comparable interface and Override compareTo() methods for class comparison, so that Collection.sort & Arrays.sort can be used for sequencing: Collections: public static int binarySearch(List<? extends T> list, T key,Comparator<? super T> c)
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
public class TestSortedSet {
public static void main(String[] args) {
SortedSet ss= new TreeSet();
ss.add("hello");
ss.add("Goodbye");
ss.add("8");
System.out.println(ss.size());
Iterator it= ss.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
- Map: Subinterfaces: {Bindings, ConcurrentMap<K,V>, ConcurrentNavigableMap<K,V>, LogicalMessageContext, MessageContext, NavigableMap<K,V>, SOAPMessageContext, SortedMap<K,V> }
- Map: pair value of (key, value) Classes: { AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap }
- HashMap: clear(), Object clone(), boolean containsKey(Object key), boolean containsValue(Object value), Set(Map, Entry<K,V> entrySet(), V get(Object key), boolean isEmpty(); Set keySet(), V put(K key, V value), void putAll(Map<?extends K, ? extends V> m), V remove(Object key), int size(), Collection(V)values(),
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class TestHashMap {
public static <E> void main(String[] args) {
HashMap<String, String> hmap= new HashMap();
hmap.put("d","doofus");
hmap.put("g","goofus");
hmap.put("z","zeefo");
System.out.println("map size "+hmap.size());
System.out.println("___");
for(Object key: hmap.keySet())
System.out.println(key);
System.out.println("___");
for(Object val: hmap.values())
System.out.println(val);
System.out.println("___");
System.out.println(hmap.get("d"));
System.out.println("___");
for(Object key: hmap.keySet())
System.out.println(hmap.get(key));
System.out.println("___");
Set<String> set= hmap.keySet();
Iterator<String> it= set.iterator();
while(it.hasNext()){
Object key=it.next();
Object val=hmap.get(key);
System.out.println(key+":"+val);
}
System.out.println("___");
System.out.println(hmap.containsKey("d"));
System.out.println(hmap.containsValue("goofus"));
System.out.println("___");
hmap.remove("d");
System.out.println("map size "+hmap.size());
}
}
import java.util.HashMap;
import java.util.Map;
public class TestHashMap2 {
public static void main(String[] args) {
Map s= new HashMap();
Student s0= new Student("StuA","male");
Student s1= new Student("StuB","female");
s.put("ab",s0);
s.put("cd",s1);
Student s2= (Student)s.get("ab");
System.out.println("ab is key for "+s2.getName()+" "+s2.getSex());
}
}
class Student{
private String name;
private String sex;
public Student(){}
public Student(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
- ArraList HashMap<K,V>: , <K,V> would not be changed into objects if defined first
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestCollection {
public static void main(String[] args) {
Student2 s0 = new Student2("StuA", "male");
Student2 s1 = new Student2("StuB", "female");
ArrayList<Student2> s = new ArrayList<Student2>();
s.add(s0);
s.add(s1);
Dog2 d0 = new Dog2("DogA", "male");
Dog2 d1 = new Dog2("DogB", "female");
ArrayList<Dog2> d = new ArrayList<Dog2>();
d.add(d0);
d.add(d1);
HashMap<String,ArrayList> map = new HashMap<String,ArrayList>();
map.put("st", s);
map.put("dog", d);
// get info
Set keys = map.keySet();
Iterator it = keys.iterator();
while (it.hasNext()) {
Object key = it.next();
Object val = map.get(key);
ArrayList l = (ArrayList) val;
for (Object v : l) {
System.out.println(v);
}
}
}
}
class Dog2 {
private String name;
private String type;
public Dog2() {
}
public Dog2(String name, String type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return "Dog2 [name=" + name + ", type=" + type + "]";
}
}
class Student2 {
private String name;
private String sex;
public Student2() {
}
public Student2(String name, String sex) {
this.name = name;
this.sex = sex;
}
@Override
public String toString() {
return "Student2 [name=" + name + ", sex=" + sex + "]";
}
}
- Iterator: Subinterfaces: {ListIterator, XMLEventReader } Classes: {BeanContextSupport.BCSIterator, EventReaderDelegate, Scanner }
- Iterator is used when the collection does not have an index, Set, Map
- Collections methods
- implements Comparable: public in compareTo (Object 0){return 0;}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestCollection2 {
public static void main(String[] args) {
List list = null;
Object key = null;
//Collections.binarySearch(list, key);//search
//Collections.sort(list);//sort
//Comparator compare = null;
//list.sort(compare);//compare
// min()/max()
ArrayList<String> st=new ArrayList<String>();
Collections.addAll(st,"hello","world","!","Sun");
System.out.println(st.size());
System.out.println("---");
for(String s: st)
System.out.println(s);
System.out.println("---");
Collections.sort(st);
for(String s: st)
System.out.println(s);
System.out.println("---");
Collections.reverse(st);
for(String s: st)
System.out.println(s);
System.out.println("---");
Dog3 d0 = new Dog3("DogA", "male",22,2);
Dog3 d1 = new Dog3("DogB", "female",44,1);
Dog3 d3 = new Dog3("Bob", "male",22,2);
Dog3 d2 = new Dog3("Alice", "female",88,3);
List<Dog3> d=new ArrayList<Dog3>();
Collections.addAll(d, d0,d1,d2,d3);
for(Dog3 dd: d)
System.out.println(dd.toString());
System.out.println("---");
Collections.sort(d);
for(Dog3 dd: d)
System.out.println(dd.toString());
System.out.println("---");
Collections.sort(d,new CompareByAge());
for(Dog3 dd: d)
System.out.println(dd.toString());
}
}
class Dog3 implements Comparable {
String name;
private String type;
int id;
int age;
public Dog3() {
}
public Dog3(String name, String type, int id, int age) {
this.name = name;
this.type = type;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "Dog3 [name=" + name + ", type=" + type + ", id=" + id + ", age" + age + "]";
}
@Override
public int compareTo(Object o) {
Dog3 d = (Dog3) o;
if (this.id == d.id)
return this.name.compareToIgnoreCase(d.name);
else {
if (this.id > d.id)
return 1;
else if (this.id == d.id)
return 0;
else
return -1;
}
}
}
class CompareByAge implements Comparator<Dog3> {
@Override
public int compare(Dog3 a, Dog3 b) {
return (a.age > b.age) ? 1 : (a.age < b.age) ? -1 : (a.name.compareTo(b.name));
}
}
Java Core 2: Enum, String ,Calendar
- Enum: class of fixed attributes: ex: State of a transaction: unpaid, paid, unsent, sent, received
public class TestEnum{
public static void main(String[] args) {
Animal a=new Animal();
a.setG(Gender.Female);
Animal b=new Animal();
b.setG(Gender.Neuter);
Animal c=new Animal();
c.setG(Gender.Male);
System.out.println(a.getG()+","+b.getG());
Order o=new Order();
int num=o.StateUnpaid();
System.out.println(o.StateUnpaid());
System.out.println(Order.OrderState.StateUnpaid);
}
}
class Order{
enum OrderState{
StateUnpaid, StatePaid()
}
int StateUnpaid(){ //not the same as StateUnpaid in Enum
return -1;
}
int StatePaid(){
return 1;
}
}
enum Gender{
Male, Female, Neuter
}
class Animal{
private Gender g;
public Gender getG() {
return g;
}
public void setG(Gender g) {
this.g = g;
}
}
public class TestEnum2 {
public static void main(String[] args) {
Subject s=Subject.Sub1;
switch(s){
case Sub1:
System.out.println(s.Sub1);
break;
case Sub2:
System.out.println(s.Sub2);
break;
case Sub3:
System.out.println(s.Sub3);
break;
}
}
}
enum Subject{
Sub1, Sub2, Sub3
}
- Wrapper class Boxing: Byte, Short, Integer, Long, Float, Double, Boolean: cast primitive to Object type
- Parse: from String to primitive: parseXXX
- ValueOf
< http://java.com?id=12>
String s= request.get…
int id=Integer.parseInt(id);
…or…
int id=Integer.valueOf(s);
Person p= new Person();
p.getPerson(id);
…
public Person getPerson (int id){
return id;
}
public class TestBox {
public static void main(String[] args) {
int n= 12;
System.out.println(n);//n is not an object, no hashcode
Integer num= new Integer("124333");
System.out.println(num.getClass()+" "+num);
System.out.println(n+" "+n);
System.out.println(n+n);
System.out.println(n==num);//false
}
}
- java.lang.Math Math.random()
- java.util.Random()
import java.util.Random;
public class TestMath {
public static void main(String[] args) {
double rand=Math.random();
System.out.println(rand);
int r=(int)(rand*10); //1~10
System.out.println(r);
r=(int)(rand*10+12);//12~22
System.out.println(r);
r=(int)(rand*5+12);//12~17
Random r2= new Random(12); //12 is seed
Random r3= new Random(12);
System.out.println(r2.nextInt());
System.out.println(r3.nextInt());
//this(seedUniquifier()^System.nanoTime())
System.out.println(r2.nextInt(10));
System.out.println(r2.nextInt(10)+12);//12~22
System.out.println(r3.nextInt(10));
System.out.println(r2.nextGaussian());
}
}
import java.util.Scanner;
public class Register {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("username: ");
String name=sc.next();
System.out.println("password: ");
String ps=sc.next();
if ("TOM".equals(name) &&"123".equals(ps))
System.out.println("Success login");
else
System.out.println("incorrect");
//equalsIgnoreCase()
//toLowerCase()
//toUpperCase()
}
}
import java.util.Scanner;
public class Login {
public static void main(String[] args) {
boolean log=false;
Scanner s= new Scanner(System.in);
do{
System.out.println("username: ");
String name=s.nextLine();
System.out.println("password: ");
String p=s.nextLine();
System.out.println("password again: ");
String p2=s.nextLine();
if(name.length()<3 && p.length()<6){
System.out.println("Name>=3, Password>=6");
}else if (!p.equals(p2)){
System.out.println("password does not match");
}else{
System.out.println("Success");
log=true;
}
}while(!log);
}
}
- String: concat(String s), int indexOf(int ch), int indexOf(String value), int lastIndexOf(int ch), int lastIndexOf(String value), String substring(int index), String substring (int begininddex, int endindex), public String trim();
public class StringTest {
public static void main(String[] args) {
String name=" admin";
System.out.println(name);
String name2=name.concat(" Controller "+ "");
System.out.println(name2);
name2=name2.concat("hello " );
System.out.println(name2);
System.out.println(name2.indexOf("a"));//Indext OF
System.out.println(name2.indexOf("mi"));
System.out.println(name2.indexOf("a",3));
System.out.println(name2.indexOf("ll",3));
System.out.println(name2.substring(3,11));
System.out.println(name2.trim());//get rid of front back spaces
System.out.println("Original: ".concat(name2));
String name3=name2;
String[] str=name2.split("o"); //split with o
for(String s:str)
System.out.println(s+" ");
System.out.println("o occurences:"+(name2.split("o").length-1)); //sections-1
Character c=name3.charAt(3);
System.out.println(c);
}
}
- StringBuffer : Threadsafe, faster than String : sb.toString(); sb.append(“xx”); sb.insert(2,“xx”)
- StringBuilder: Not Threadsafe, faster than StringBuffer, fastest
public class StringBufferTest {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
String str = null;
StringBuilder s=new StringBuilder();
long start=System.currentTimeMillis();
for(int i=0; i<20000;i++){
str=str+i;
}
long end=System.currentTimeMillis();
System.out.println("String time: "+(end-start));//1746 nanoseconds
start=System.currentTimeMillis();
for(int i=0; i<20000;i++){
sb=sb.append(i);
}
end=System.currentTimeMillis(); //3 nanoseconds
System.out.println("StringBuffer time: "+(end-start));
start=System.currentTimeMillis();
for(int i=0; i<20000;i++){
s=s.append(i);
}
end=System.currentTimeMillis(); //3 nanoseconds
System.out.println("StringBuilder time: "+(end-start));
sb.append("hello");
sb.insert(0, " rabbit ");
System.out.println(sb.toString());
}
}
public class StringBufferTest2 {
public static void main(String[] args) {
StringBuffer s=new StringBuffer("123456789");
for(int i=s.length()-3;i>0;i=i-3)
s.insert(i,",");
System.out.println(s);
}
}
- Date: java.util.Date
- SimpleDateFormat . format(date) ; parse(String)
- java.text.SimpleDateFormat
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, …, 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
“yyyy.MM.dd G ‘at’ HH:mm:ss z” 2001.07.04 AD at 12:08:56 PDT
“EEE, MMM d, ''yy” Wed, Jul 4, '01
“h:mm a” 12:08 PM
“hh ‘o’‘clock’ a, zzzz” 12 o’clock PM, Pacific Daylight Time
“K:mm a, z” 0:08 PM, PDT
“yyyyy.MMMMM.dd GGG hh:mm aaa” 02001.July.04 AD 12:08 PM
“EEE, d MMM yyyy HH:mm:ss Z” Wed, 4 Jul 2001 12:08:56 -0700
“yyMMddHHmmssZ” 010704120856-0700
“yyyy-MM-dd’T’HH:mm:ss.SSSZ” 2001-07-04T12:08:56.235-0700
“yyyy-MM-dd’T’HH:mm:ss.SSSXXX” 2001-07-04T12:08:56.235-07:00
“YYYY-'W’ww-u” 2001-W27-3
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateTest {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("y-M-d H:m:s");
String time="2020-3-32 4:33:22";
try {
System.out.println(sdf.parse(time)); // parse
System.out.println(sdf.format(date)); // format
} catch (ParseException e) {
e.printStackTrace();
}
}
}
- Calendar: java.util.Calendar: Calendar c= Calendar.getInstance();
- MONTH DAY_OF_MONTH DAY_OF_WEEK : int get(int field)
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class CalendarTest {
public static void main(String[] args) {
Calendar c= Calendar.getInstance();
System.out.println(c);
int week=c.get(Calendar.WEEK_OF_YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DAY_OF_YEAR);
System.out.println("week of year: "+week);
System.out.println("month of year: "+month);
System.out.println("day of year: "+day);
}
}
Java Core 3: IO & File
- BufferedReader ; PrintWriter
public class LuckyNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N= (int)(Math.random()*10);
int num=1000;
while(num>=1000){
System.out.println("Enter 4 dig num: ");
num=sc.nextInt();
int hundreds=num/100%10;
if(hundreds==N)
System.out.println("You Win!");
else
System.out.println("Thanks");
N= (int)(Math.random()*10);
}
}
}
- IO Stream
- File: java.io.File, *.txt, FileName
- File: createNewFile() getPath() exist() mkdir() list()
import java.io.File;
public class FileTest {
public static void main(String[] args) {
new FileTest().show();
System.out.println("...");
File f=new File("D:/test");
new FileTest().show2(f);
}
void show() {
File f = new File("D:/test");
if (f.isDirectory()) {
String[] files = f.list();
for (String f1 : files)
System.out.println(f1);
}
}
void show2(File f){//list nested files
File[] fs=f.listFiles();
for(File f2:fs){
if(f2.isDirectory()){
show2(f2);
}
System.out.println(f2.getName());
}
}
}
- FileFilter: import java.io.FilenameFilter; override accept
import java.io.File;
import java.io.FilenameFilter;
public class FileTest2 {
public static void main(String[] args) {
new FileTest2().show3();
}
void show3() {
File f = new File("D:/test");
File[] fs = f.listFiles(new MyFileFilter());
for (File f1 : fs)
System.out.println(f1);
}
}
class MyFileFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(".java"))
return true;
return false;
}
}
- nested class
import java.io.File;
import java.io.FilenameFilter;
public class FileTest3 {
public static void main(String[] args) {
new FileTest3().show4();
}
private void show4(){
File f = new File("D:/test");
File[] fs = f.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(".java"))
return true;
return false;
}
});
for (File f1 : fs)
System.out.println(f1.getName());
}
}
- IOStream: InputStream(Reader); OutputStream(Writer): FIFO
- Char Stream; Byte Stream; Node Stream; Filter Stream (Buffer)
- InputStream: int read(), int read(byte[] b), int read(byte[] b, int off, int len), void close(), int available
- InputStream: FileInputStream(File file), FileInputStream(String name)
- InputStream: interface: Closeable; children: AudioInputStream, BytreArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
- OutputStream: void write(int c); void write(byte[] buf); void write(byte[] b, int off, int len); void close(); void flush
- OutputStream: FileOutputStream(File file); FileOutputStream(String name); FIleOutputStream(String name, boolean append);
- OutputSTream: interaface: Closeable, Flushable, AutoCloseable; children: ByteArrayOutputStream, FileOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOTest {
public static void main(String[] args) {
FileInputStream fis = null;
FileInputStream fis2 = null;
FileOutputStream fos=null;
try {
// create InpuStream
File fdir = new File("D:\\test\\testIO");
File f = new File("D:\\test\\testIO\\testIO.txt");
fdir.mkdir();
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//create inputStream
fis = new FileInputStream("D:\\test\\testJ.java");
fis2 = new FileInputStream("D:\\test\\testJ.java");
fos=new FileOutputStream("D:\\test\\testIO\\testIO.txt");
//set length to exit Stream
int len = 0;
//create byte for input
byte[] b = new byte[1024];
while (len != -1)
len = fis.read(b);
System.out.println("Len1 " + len);
System.out.write(b);
//second input
while ( (len=fis2.read(b)) > 0) {
System.out.println("\n\nLen2 " + len);
System.out.write(b, 0, len);
}
System.out.println("\nLen3 " + len);
System.out.write(b);
//outputSTream
fos.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fis!=null)
try {
fis.close();
fis2.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Reader: FileReader: InputStreamReader(InputStream in), InputStreamReader(InputStream in, String charsetName), BufferReader, Charset
- Reader: int read(), int read(char[] c) read(char[] c, int off, int len) void close
- must include encoding: System.out.println(System.getProperties(“file.encoding”));
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderTest {
//main
public static void main(String[] args) {
FileReader fr= null;
FileWriter fw= null;
try {
fr=new FileReader("D:\\test\\testIO\\testIO.txt");
fw=new FileWriter("D:\\test\\testIO\\testIO2.txt");
char[] c=new char[1024];
int len=0;
while((len=fr.read(c))>0)
fw.write(c, 0, len);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fr.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- BufferedInputStream: readLine()
- BufferedOutputStream
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedInputStreamTest {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
BufferedInputStream bis= null;
BufferedOutputStream bos=null;
FileInputStream fis2=null;
FileOutputStream fos2=null;
try {
fis=new FileInputStream("D:\\test\\JDK_API_7.0.CHM");
bis=new BufferedInputStream(fis);
fos=new FileOutputStream("D:\\test\\testIO\\testIO3.CHM");
fis2=new FileInputStream("D:\\test\\JDK_API_7.0.CHM");
bos=new BufferedOutputStream(fos);
fos2=new FileOutputStream("D:\\test\\testIO\\testIO4.CHM");
System.getProperty("fis2.encoding");
byte[] b=new byte[1024];
int len=0;
//time
long start = System.currentTimeMillis();
try {
while((len=bis.read(b))>0){
bos.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
long end =System.currentTimeMillis();
System.out.println("BufferedInputStream: "+(end-start));
start = System.currentTimeMillis();
try {
while((len=fis2.read(b))>0){
fos2.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
end =System.currentTimeMillis();
System.out.println("FileInputStream: "+(end-start));
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
if(bis!=null)bis.close();
if(bos!=null)bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java Core 4: Multithreads
- join yield sleep, synchronized
- new BufferedReader(new FileReader(“foo.in”))
- InputStreamReader: Read String
- FileInputStream fis=new FileInputStream(“foo.in”);
- InputStreamReader fr= new InputStreamReader(fis,“UTF-8”);
- BufferedReader br = new BufferedReader(fr);
- Project properties: Resource: text File Encoding: Other: …change base on file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedReaderTest {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw=null;
try {
br = new BufferedReader(new FileReader("D:\\test\\testIO\\testIO.txt"));
bw= new BufferedWriter(new FileWriter("D:\\test\\testIO\\testIO3.txt"));
String s= null;
while((s=br.readLine())!=null){
System.out.println(s);
bw.write(s,0,s.length());
bw.newLine();//enter
}
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (br!=null)br.close();
if (bw!=null)bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Writer: write(String str), write(String st, int off, int len); void close(); void flush();
- br=new BufferedReader(new InputStreamReader(new FileInputStream(“D:\path”), “utf-8”)); String s=br.read(); br.flush; br.close;
- OutputStreamWriter(OutputStream out) OutputStreamWriter(Outputstream out, String charsetName)
- Writer fw= new FileWriter(“foo.txt”); fw.write;
- BufferedWriter
- Eclipse: select try catch block, RightClick , surround with …select try-catch
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class InpuStreamReaderTest {
public static void main(String[] args) {
BufferedReader br= null;
try {
br=new BufferedReader(new InputStreamReader(new FileInputStream("D:\\Test\\TestIO\\testIO2.txt"), "utf-8"));
String s=null;
while((s=br.readLine())!=null)
System.out.println(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (br!=null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- System.out
import java.io.PrintWriter;
public class MySystem {
public static PrintWriter out;
public static PrintWriter getOut() {
return out;
}
public static void setOut(PrintWriter out) {
MySystem.out = out;
}
}
class TestMysSys{
public static void main(String[] args) {
System.out.println(MySystem.out);
}
}
- FileInputStream>DataInputStream (Byte) use for images etc
- DataInputStream ds=new DataInputStream(new FileInputStream(“D:\path”)); ds.read
- FileOutputStream>DataOutputStream (Byte)
- byte[] b=new byte[1024]; find image; do not close stream
- …Writer …Reader (charArray)
- binary
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataInputTest {
public static void main(String[] args) {
DataInputStream dis= null;
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("D:\\test\\testIO\\test.bin"));
dos.write(256); // byteArray largest byte
dos.write(255);
dos.writeInt(23);
dos.writeLong(33);
dos.flush(); //clear dos without closing
dis= new DataInputStream(new FileInputStream("D:\\test\\testIO\\test.bin"));
System.out.println(dis.read());
System.out.println(dis.read());
System.out.println(dis.readInt());
System.out.println(dis.readLong());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- image
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageIOTest {
public static void main(String[] args) {
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
bis= new BufferedInputStream(new FileInputStream("D:\\test\\testIO\\(^_^).jpg"));
bos=new BufferedOutputStream(new FileOutputStream("D:\\test\\testIO\\(^-^).jpg"));
byte[] b=new byte[1024];
int len=0;
while ((len=bis.read(b))>-1)
bos.write(b,0,len);
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bis!=null) bis.close();
if(bos!=null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- System.in
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamStandard {
public static void main(String[] args) {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
String s = null;
try {
while ((s = br.readLine()) != null) {
if ("quit".equals(s))
break;// getout of loop
System.out.println(s);
}
System.out.println("BYE!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Serializable: Serializable interface, ObjectStreamOut: writeObject(): close ObjectStream
- turn object into stream and vice versa: implement Serializable use ArrayList or other collection method to store Objects, then read or write using .data file
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ObjectOutputStreamTest {
public static void main(String[] args) {
ObjectOutputStream oos = null;
ObjectOutputStream oos2 = null;
ObjectInputStream ois = null;
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream("D:\\test\\testIO\\(^_^).jpg"));
oos = new ObjectOutputStream(new FileOutputStream("D:\\test\\testIO\\O_O.data"));
byte[] b = new byte[1024];
int len = 0;
while ((len = bis.read(b)) > -1)
oos.writeObject(b);
oos.flush();
oos2 = new ObjectOutputStream(new FileOutputStream("D:\\test\\testIO\\Student.data"));
St s = new St(1, "Tom", 22, "Kansas");
St s2 = new St(123, "Bob", 32, "NYC");
St s3 = new St(16, "Seth", 42, "Toronto");
List<St> sl = new ArrayList<St>();
sl.add(s);
sl.add(s2);
sl.add(s3);
oos2.writeObject(sl);
oos2.flush();
ois = new ObjectInputStream(new FileInputStream("D:\\test\\testIO\\Student.data"));
List<St> sl2 = (List<St>) ois.readObject();
if (sl2 != null && sl2.size() > 0) {
for (St s1 : sl2)
System.out.println(s1.getClass()+":" + s1.getName());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (bis != null)bis.close();
if(ois!=null) ois.close();
if(oos!=null) oos.close();
if(oos2!=null) oos2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class St implements Serializable {
private int id;
private String name;
private int age;
private String address;
St() { }
St(int id, String name, int age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- Processes are used to group resources together (address space)(APP); threads are the entities scheduled for execution on the CPU (stack) (Single/Multi)(List of operations steps) (main, exception)
- Multithreads: java.lang.Threads; java.lang.Runnable
- create class for threads (extends Thread implements Runnable): create thread object in main: Override runnable: run threads
- Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc.
public class ThreadTest {
public static void main(String[] args) {
MyThread m= new MyThread();
m.start();
for(int i=0;i<10;i++)
System.out.println("main = "+i);
}
}
class MyThread extends Thread{
@Override
public void run() {
for(int i=0; i<10; i++)
System.out.println("Thread ="+i);
}
}
- thread can extend to other threads
public class ThreadTest {
public static void main(String[] args) {
MyThread m= new MyThread();
Thread t= new Thread(m); //static proxy
MyThread2 m2= new MyThread2();
m.start();
t.start();
m2.start();
for(int i=0;i<10;i++) //main thread implemented first
System.out.println("main = "+Thread.currentThread()+i);
}
}
class MyThread extends Thread implements Runnable{
@Override
public void run() {
int i=10;
while(i>0){
System.out.println("Thread = "+ Thread.currentThread()+i);
i--;
}
}
}
class MyThread2 extends Thread implements Runnable{
@Override
public void run() {
for(int i=0; i<10; i++)
System.out.println("Thread2 = "+ Thread.currentThread()+i);
}
}
- new thread: create Thread> runnable thread: CPU prepare to run> running thread: start> not runnable thread: join(), yield(), sleep() , I/O > dead: end normal state, not normal: stop(), destroy()
- use boolean to stop thread flag- false/true
- daemon thread in Java is a thread that runs in the background within same process. Daemon threads are like Service providers for other threads running in the same process.
- setPriority(): 1-10
public class Thread3Test {
public static void main(String[] args) {
for(int i=0; i<10;i++)
System.out.println(Thread.currentThread().getName()+i);
TestThread t= new TestThread();
t.setName("test");
Thread t1= new Thread(t);
t1.setPriority(Thread.MIN_PRIORITY);
t1.setName("Thread");
t1.setPriority(Thread.MAX_PRIORITY);
t1.start();
t.start();
}
}
class TestThread extends Thread implements Runnable{
@Override
public void run() {
for(int i=10; i<20;i++)
System.out.println(Thread.currentThread().getName()+i);
}
}
- join()
public class Thread2Test {
public static void main(String[] args) {
new Thread2Test().runThread();
}
private void runThread() {
System.out.println(Thread.currentThread().getName()+"start...");
JoinThread jt=new JoinThread();
Thread t1=new Thread(jt, "Dog");
Thread t2=new Thread(jt,"Cat");
t1.start();
t2.start();
try {
t1.join(); //make sure finish before main finishes
t2.join(); //main thread waits the joined threads finish before it finishes
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"finish...");
}
class JoinThread implements Runnable{
@Override
public void run() {
for(int i=0; i<10; i++)
System.out.println(Thread.currentThread().getName()+i);
}
}
}
- yield: become runnable thread: yeild to higher priority thread with condition
public class ThreadYieldTest {
public static void main(String[] args) {
new ThreadYieldTest().runThread();
}
public void runThread() {
YieldThread yt = new YieldThread();
Thread t1 = new Thread(yt, "Bob");
Thread t2 = new Thread(yt, "Tom");
Thread2 t= new Thread2();
Thread t3 = new Thread(t, "Sam");
t1.start();
t3.setPriority(10);
t2.start();
t3.start();
}
class YieldThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (i >= 3) {
Thread.yield();
}
System.out.println(Thread.currentThread().getName() + i);
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName() + i);
}
}
}
- sleep:
import java.text.SimpleDateFormat;
import java.util.Date;
public class SleepThreadTest {
public static void main(String[] args) {
SimpleDateFormat sdf= new SimpleDateFormat("hh:mm:ss");
Date endTime=new Date(System.currentTimeMillis()+10*1000);
long end=endTime.getTime();
String now;
for(int i=0; i<10; i++){
endTime= new Date(end);
now=sdf.format(endTime);//format now
System.out.println(now);
System.out.println(end);//long endtime.getTime();
end-=1000; //1000=1 second for milliseconds
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- Synchronized method, or block: prevent competition of threads
- public synchronized void run()
public class SynchronizedTest {
public static void main(String[] args) {
Tickets t = new Tickets();
Thread t1 = new Thread(t, "t1");
Thread t2 = new Thread(t, "t2");
Thread t3 = new Thread(t, "t3");
t1.start();
t2.start();
t3.start();
}
}
class Tickets implements Runnable {
int t = 1000;
@Override
public void run() { //or put synchronized before void (public synchronized void run())
while (t > 0) {
synchronized (this) {
if(t>0)
System.out.println(Thread.currentThread().getName() + ":" + (t--));
}
}
}
}
- DeadLock: thread wait for each other’s lock: synchronized inside other synchronized: avoid
public class DeadLockTest {
public static void main(String[] args) {
new DeadLockTest().runThread();
}
class DLThread implements Runnable {
private Object key1 = new Object();
private Object key2 = new Object();
boolean flag = true;
@Override
public void run() {
if (flag) {
synchronized (key1) {//key1 wait for key2 to finish
flag = false;
System.out.println(Thread.currentThread().getName() + ": key1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (key2) {
System.out.println(Thread.currentThread().getName() + ": key2");
}
}
} else {
flag = true;
synchronized (key2) {
System.out.println(Thread.currentThread().getName() + ": f key2");
synchronized (key1) {
System.out.println(Thread.currentThread().getName() + ": f key1");
}
}
}
}
}
public void runThread(){
DLThread d=new DLThread();
Thread t1=new Thread(d,"Bob");
Thread t2=new Thread(d,"Ken");
t1.start();
t2.start();
}
}
- producer and consumer problem : Produce one then buy one
- notify …wait … synchronized: wait for one thread to finish before starting another one
import java.util.Random;
public class SynchTest {
public static void main(String[] args) {
Dish d = new Dish();
Cook coo = new Cook("Allan", d);
Customer c = new Customer("Sam", d);
Thread cooking = new Thread(coo);
Thread eating = new Thread(c);
//set Daemon thread
eating.setDaemon(true);
cooking.start();
eating.start();
}
}
class Cook implements Runnable {
private String name;
private String food;
private String[] f;
private Dish d;
Random rand = new Random();
public Cook(String name, Dish d) {
this.name = name;
this.d = d;
f = new String[] { "dish1: pasta", "dish6: pizza", "dish2: chicken", "dish3: tofu", "dish4: steak", "dish5: eggs" };
}
public void cookf() throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println("cook" + (i+1));
synchronized (d) {
if (d.isEmpty()) {
int index = rand.nextInt(f.length);
String food = f[index];
System.out.println(name + " cooking " + food);
d.setFood(food);
d.setEmpty(false);
d.notify();//wake customer
d.wait();//cook wait
}else
d.wait();
}
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public String[] getF() {
return f;
}
public void setF(String[] f) {
this.f = f;
}
public Dish getD() {
return d;
}
public void setD(Dish d) {
this.d = d;
}
@Override
public void run() {
try {
cookf();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Dish {
private String food;
private boolean isEmpty = true;
public Dish() {
}
public Dish(String food) {
this.food = food;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
public boolean isEmpty() {
return isEmpty;
}
public void setEmpty(boolean isEmpty) {
this.isEmpty = isEmpty;
}
}
class Customer implements Runnable {
private String name;
private Dish d;
public void eat() throws InterruptedException {
while(true) { //Daemon thread true false
synchronized (d) {
if (!d.isEmpty()) {
System.out.println(name + " eating " + d.getFood());
Thread.sleep(1000);//for display purpose
d.setEmpty(true);
d.notify(); //wake cook
d.wait(); //customer wait
} else
d.wait();//cusomer wait
}
}
}
public Customer(String name, Dish d) {
this.name = name;
this.d = d;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dish getD() {
return d;
}
public void setD(Dish d) {
this.d = d;
}
@Override
public void run() {
try {
eat();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- notify …wait … synchronized: wait for one thread to finish before starting another one
public class ClockTest {
public static void main(String[] args) {
Clock c = new Clock();
Thread ct = new Thread(c);
Thread ht = new Thread(new Human("Sam", c));
ht.setDaemon(true);// make sure first loop goes in to run block
ct.start();
ht.start();
}
}
class Clock implements Runnable {
private boolean ring = false;
public void ring() throws InterruptedException {
for (int t = 0; t < 5; t++) {
synchronized (this) {
System.out.println("wake up"); //try block executed first
if (!ring) {// if human woke once or ring=false
for (int i = 0; i <3; i++) {
System.out.println("ring"+ i+ t);
}
ring = true; // allow human to wake
Thread.sleep(1000);
this.notify();// human notify
this.wait();// clock wait
} else
this.wait();// clock wait
}
}
}
@Override
public void run() {
try {
ring();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean isRing() {
return ring;
}
public void setRing(boolean ring) {
this.ring = ring;
}
}
class Human implements Runnable {
private String name;
private Clock c;
public Human(String name, Clock c) {
this.name = name;
this.c = c;
}
public void wake() throws InterruptedException {
synchronized (c) {
if (c.isRing()) {// if clock rang already
System.out.println(name +" "+ c.isRing()+" ... waking up");
c.setRing(false); // allow clock to ring
Thread.sleep(1000);
c.notify(); // wake clock
c.wait();// human wait
} else
c.wait();// human wait
}
}
@Override
public void run() {
while (true)// respond to daemon thread
try {
wake();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Java Core 5: Web, Socket, DatagramSocket
- Web: connect computers, share exchange data
- OSI: Open System Interconnection
- 7 leves: (Site: FTP > Expression zip, img > Dialogue) > (ExchangeTCP: UDP) > (Internet IP ) >(dataConnect > hardware)
- IP: Address: Internet protocol: 32 digits: 4 8 digit binary : 192.168.226.134 : find computer
- website: www.hello.com:90; www.hello.com:90: find portal ex.portal: 1024 max 65535
- telnet: 21 ftp:23
- cmd: ipconfig: your own computer : computer self reference: 127.0.0.1 localhost skuipped from A to B
- cmd: ping: destination IP: IPv4
- linux: ifconfig; ping
- C:\Windows\System32\Drivers\etc\hosts :
#localhost name resolution is handled within DNS itself.
#127.0.0.1 localhost
#::1 localhost
- Domain Name System
- java.net package: Socket; ServerSocket; DatagramPacket; DatagramSocket; InetAddress
- TCP Socket : set Encoding to UTF-8 under properties
- TCP: Run Server first, then Client
- Socket. getInetAddress().getHostAddress(): IP
- Socket: getPort(): random generated address
- Socket: getLocalPort():User named portname
- Socket: can user I/O Stream with PrintWriter BufferedReader
- Client: Socket s; Socket contains the InetAddress
String str="Hello!"; PrintWriter out= new PrintWriter(s.getOutputStream(),true); out.println(str);
- Server: ServerSocket ss; Socket s
BufferedReader br= new BufferedReader(new InputStreamReader(s.getInputStream())); String str= br.readLine(); Println(br);
- If encounter error: java.net.BindException: Address already in use
cmd: netstat -p tcp -ano | findstr :8888
-
PID can be found under application details of process(ctl alt delete): close it
-
Server Socket
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(8888); // create serversocket
Socket s = ss.accept();// accept clientsocket
System.out.println("Server Socket connected to client");
// read string message sent by client
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine();
System.out.println(str);
System.out.println(s.getInetAddress().getHostAddress() + ":" + s.getPort() + ":" + s.getLocalPort());
// send message back
String str2 = "ServerSocket To client message got:" + str;
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println(str2);
// get message from input
String str3 = "";
while ((str3=br.readLine())!=null) {
if ("exit".equals(str3)) {
System.out.println("Exit!");
break;
}else{
System.out.println(str3);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null)
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Client Socket
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
Socket s = null; // create socket
try {
s = new Socket("127.0.0.1",8888); // accept current computer as
// host and created 8888 port as
// entry point
String str="Client to Server: Hello!";
PrintWriter out= new PrintWriter(s.getOutputStream(),true);
out.println(str);
//get message from server
BufferedReader br= new BufferedReader(new InputStreamReader(s.getInputStream()));
String strs=br.readLine();
System.out.println(strs);
//send message from input
BufferedReader br2=new BufferedReader(new InputStreamReader(System.in));
String str2=null;
while((str2=br2.readLine())!=null){
out.println(str2);
if("exit".equals(str2)){
System.out.println("get Offline...");
break;
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Server (Cleaned Up)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server3 {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(8888);
while (true) { // for accepting multiple clients
s = ss.accept();
String name = s.getInetAddress().getHostAddress() + " : " + s.getPort();
System.out.println(name + " is online");
BufferedReader br= new BufferedReader(new InputStreamReader(s.getInputStream()));
String str=null;
while((str=br.readLine())!=null){
if("bye".equals(str)){
System.out.println("Client breaks: "+str);
break;
}
System.out.println(name+ " Client Sent: "+str);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null)
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Client (Cleaned Up)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client3 {
public static void main(String[] args) {
Socket s=null;
try {
s= new Socket("127.0.0.1",8888);
PrintWriter out= new PrintWriter(s.getOutputStream(),true);//write into socket s
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));//reader
String str=null;
while((str=br.readLine())!=null){ //buffer give to str, read system in
if("quit".equals(str)){
out.println("bye");
break; //reading breaks if =quit
}
out.println(str);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- TCP (Transmission Control Protocol(HTTP, HTTPs, FTP, SMTP, Telnet)(SYN, SYN-ACK, ACK)) Transmission Control Protocol is a connection-oriented protocol.Data is read as a byte stream, no distinguishing indications are transmitted to signal message (segment) boundaries.
- TCP gives guarantee that the order of data at receiving end is same as on sending end while UDP has no such guarantee.
- Header size of TCP is 20 bytes while that of UDP is 8 bytes.
- TCP is heavy weight as it needs three packets to setup a connection while UDP is light weight.
- UDP( User Datagram Protocol(DNS, DHCP, TFTP, SNMP, RIP, VOIP.)( No handshake (connectionless protocol))) (Walkie-talkies): UDP is also a protocol used in message transport or transfer. This is not connection based which means that one program can send a load of packets to another and that would be the end of the relationship.Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent.
- UDP uses: DatagramPacket(); DatagramSocket() to send and receive message
- UDP: getdata(); send(), receive();
- DatagramSocket receive(DatagramPacket(byte buf)); DatagramSocket send(DatagramPacket(byte buf))
- Sender:DatagramSocket contains different InetAddress, local address, from DatagramPacket ; ok as long as Receiver local address matches with Sender DatagramPacket Adress
- Run Receiver first then Sender ( one way)
- Sender
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Sender {
public static void main(String[] args) {
DatagramSocket ds= null;
try {
ds= new DatagramSocket(6666);
String str= "Message from Sender";
byte[] buf=str.getBytes();
DatagramPacket dp= new DatagramPacket(buf, 0, buf.length, InetAddress.getByName("127.0.0.1"),8888);
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(ds!=null)
ds.close();//close socket
}
}
}
- Receiver
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class Receiver {
public static void main(String[] args) {
DatagramSocket ds=null;
try {
ds=new DatagramSocket(8888);
byte[] buf= new byte[1024];
DatagramPacket dp= new DatagramPacket(buf, 0, buf.length);
ds.receive(dp);;
String str= new String(buf,0, buf.length);
System.out.println("Receiver gets: "+ str);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (ds!=null) ds.close(); //close socket
}
}
}
- MultiThread Server: one Server connect to multiple Clients
- Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server3 {
public static void main(String[] args) {
try {
new Server3().start();
} catch (IOException e) {
e.printStackTrace();
} //run
}
void start() throws IOException { //create new socket
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(8888);
while (true) {
s = ss.accept();
ServerThread st = new ServerThread(s);
new Thread(st).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null)
s.close(); //close socket
}
}
}
class ServerThread implements Runnable {
String name;
BufferedReader br = null;
public ServerThread(Socket s) throws IOException { //declare thread existance
name = s.getInetAddress().getHostAddress() + " : " + s.getPort();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(name + " is online");
}
@Override
public void run() {
String str=null;
try {
while ((str = br.readLine()) != null) {//output client input
if ("bye".equals(str)) {
System.out.println(name+" Client breaks: " + str);
break;
}
System.out.println(name+" Client Sent: " + str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- MultiThread Server: one Server connect to multiple Clients
- Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client3 {
public static void main(String[] args) {
Socket s=null;
try {
s= new Socket("127.0.0.1",8888);
PrintWriter out= new PrintWriter(s.getOutputStream(),true);//write into socket s
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));//reader
String str=null;
while((str=br.readLine())!=null){ //buffer give to str, read system in
if("quit".equals(str)){
out.println("bye");
break; //reading breaks if =quit
}
out.println(str);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- chat room
- MultiThread Client: one Server connect to multiple Clients: clients also reads from Server
- Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
public class Server3 {
List<ServerThread> clients = new ArrayList<ServerThread>();
public static void main(String[] args) {
try {
new Server3().start();
} catch (IOException e) {
e.printStackTrace();
} // run
}
void start() throws IOException { // create new socket
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(8888);
while (true) {
s = ss.accept();
ServerThread st = new ServerThread(s);
new Thread(st).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null)
s.close(); // close socket
}
}
class ServerThread implements Runnable {
String name;
BufferedReader br = null;
PrintWriter out = null; // for multiple inputs inside list
public ServerThread(Socket s) throws IOException { // declare thread existance
name = s.getInetAddress().getHostAddress() + " : " + s.getPort();
out = new PrintWriter(s.getOutputStream(),true);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
name = br.readLine() + "[" + name + "]";
System.out.println(name + " is online");
clients.add(this); // add into collection
send(name + " is online");
}
public void send(String str) { // // clients
for (ServerThread st : clients) {
st.out.println(str); // send to client
}
}
@Override
public void run() {
String str = null;
try {
while ((str = br.readLine()) != null) {// output client input
if ("bye".equals(str)) {
send(name + " Client breaks: " + str);
clients.remove(this); //client removed
System.out.println(name + " Client breaks: " + str);
break;
}
send(name + " Client Sent: " + str);
System.out.println(name + " Client Sent: " + str);
}
} catch (SocketException e) { // catch client quit without enteringquit
System.out.println(name + " SockeException detected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- chat room
- MultiThread Client: one Server connect to multiple Clients: clients also reads from Server
- Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client3 {
Socket s = null;
boolean flag = true;
public static void main(String[] args) {
new Client3().start();
}
public void start() {
try {
s = new Socket("127.0.0.1", 8888);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
// write into socket
new Thread(new ClientThread()).start();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));// reader
String str = null;
String welcome = "Turtle3";
out.println(welcome);
// print in client from server
while (((str = br.readLine()) != null) && flag) { // buffer give to str, read
// system in
if ("quit".equals(str)) {
out.println("bye");
flag=false; //get out of loop
break;
}
out.println(str);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientThread implements Runnable {
BufferedReader br2 = null;
@Override
public void run() { //only for reading from server
try {
while (true) { // get msgs from Server
br2 = new BufferedReader(new InputStreamReader(s.getInputStream()));
// read from server
System.out.println( br2.readLine());
if(!flag) break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java Core 6: XML, DOM, dom4J
- <? xml version = " " encoding=" "?>
- < element attribute=“attribute”>var< /element>
- one var can have multiple fields
- < “attribute” >cannot contain " < , & (’,> not recommended)
- XML (eXtensible Markup Language) : exchange data, basis & structure for Ajax; *.xml
- HTML ( Hyper Text Markup Language)
- xmlns: XML Namespaces~ Package in java
- basic list XML
<?xml version="1.0" encoding="UTF-8"?>
<clothes>
<Size size= "XS" height="heigt <165"></Size>
<Size size= "S" height="165 > heigt <170"></Size>
<Size size= "M" height="170 > heigt <175"></Size>
<Size size= "L" height="175 > heigt <180"></Size>
<Size size= "XL" height="180 > heigt <185"></Size>
<Size size= "XXL" height="185 > heigt <190"></Size>
</clothes>
- Parse: read contentswithin the XML: DTD Document Type Definition
- Parse: DOM: costly: tree parse
- Parse: SAX: event parse
- Parse: Dom4J: good for Java
- Spring < beans/> < img />
<?xml version="1.0" encoding="UTF-8"?>
<Students>
<!-- attribute based list -->
<Student name="Bob" age="36" expectedScore="76" score="90"></Student>
<!-- comments -->
<!-- node based list -->
<Student>
<name>Bob</name>
<age>36</age>
<expectedScore>76</expectedScore>
<score>90</score>
</Student>
</Students>
- DOM(Document Object MOdel); node based vs attribute based
- org.w3c.dom
- Attr ; CDATASection ; CharacterData ; Comment ;Document ; DocumentFragment ; DocumentType ; DOMConfiguration ; DOMError ; DOMErrorHandler ; DOMImplementation ; DOMImplementationList ; DOMImplementationSource ; DOMLocator ; DOMStringList ; Element ; Entity ; EntityReference ; NamedNodeMap ; NameList ; Node ;NodeList ;Notation ; ProcessingInstruction;Text; TypeInfo ; UserDataHandler
- DOM parse: does not require any extra jar packages: package> export>jar ( war )
- Documet: NodeList; getElementsByTagName(String Tag); Element CreateElement(String tagName)
- Node: NodeList getChildNodes()
- Element: String getTagName()
- DocumentBuilderFactory; DocumentBuilder : javax.xml.parsers.: parse Stream
- Turn XML into Document
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMTest {
public static void main(String[] args) {
// 1. create Parser Factory Object
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
// 2. use factory to create Builder(Parser)
try {
DocumentBuilder b = f.newDocumentBuilder();
// 3. use Builder(parser) to create Document Object from XML
Document doc = b.parse(new File("src/com/bf/javacore/Phone.xml"));
System.out.println(doc);// print
// 4. start parsing
NodeList nl=doc.getElementsByTagName("Brand");
System.out.println("# of Nodes: "+nl.getLength());
NodeList nl2=doc.getChildNodes();
for(int i=0; i<nl.getLength();i++){
Node n=nl.item(i);
Element e= (Element)n;
String name=e.getAttribute("name");
System.out.println(name);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- TranformerFactory; Tranformer; StreamResult; DOMSource: XML
- write XML into another Document
import java.io.File;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class DOMTest2 {
public static void main(String[] args) {
//1.create TranformerFactory
TransformerFactory tf=TransformerFactory.newInstance();
//2. create Tranformer
try {
Transformer t= tf.newTransformer();
//3.create Output Stream
//4. create StreamResult
StreamResult sr= new StreamResult(new File("src/com/bf/javacore/new_phone.xml"));
//5. create DOMsource
DOMSource ds= new DOMSource();
//6.tranform DOMsource into StreamResult
t.transform(ds,sr);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}
- Add Element into XML file
- Update Element in XML
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMTest3 {
Document doc = null;
public DOMTest3() {
try {
// 1. create Parser Factory Object
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
// 2. use factory to create Builder(Parser)
DocumentBuilder b = f.newDocumentBuilder();
// 3. use Builder(parser) to create Document Object from XML
doc = b.parse(new File("src/com/bf/javacore/Phone.xml"));
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addElement() {
// check root elements in doc
Element root = doc.getDocumentElement();
System.out.println(root.getNodeName());
// Create Brand node
Element e = doc.createElement("Brand");
// set name attribute for Brand
e.setAttribute("name", "Samsung");
// Create Type node
Element typeE = doc.createElement("Type");
// set name Attribute for Type
typeE.setAttribute("name", "Note88");
// add node Type under Brand
e.appendChild(typeE);
// add node Brand under PhoneInfo
root.appendChild(e);
// tranform nodes into file
}
// update new id node into doc: Brand
public void updateElement() {
NodeList list = doc.getElementsByTagName("Brand");
for (int i = 0; i < list.getLength(); i++) {
Element e = (Element) list.item(i);
e.setAttribute("id", (i + 1) + " ");
}
//save
saveXML("src/com/bf/javacore/new_phone.xml");
}
//deleteElement
public void deleteElement(){
NodeList list = doc.getElementsByTagName("Brand");
for (int i = 0; i < list.getLength(); i++) {
Element e = (Element) list.item(i);
if("Apple".equals(e.getAttribute("name")))
e.getParentNode().removeChild(e);
}
//save
saveXML("src/com/bf/javacore/new_phone.xml");
}
// save
public void saveXML(String path) {
try {
// 1.create TranformerFactory
TransformerFactory tf = TransformerFactory.newInstance();
// 2. create Tranformer
Transformer t = tf.newTransformer();
// 3.create Output Stream
// 4. create StreamResult
StreamResult sr = new StreamResult(new File(path));
// 5. create DOMsource
DOMSource ds = new DOMSource(doc);
// 6.tranform DOMsource into StreamResult
t.transform(ds, sr);
} catch (TransformerConfigurationException e1) {
e1.printStackTrace();
} catch (TransformerFactoryConfigurationError e1) {
e1.printStackTrace();
} catch (TransformerException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
DOMTest3 dt = new DOMTest3();
dt.addElement();
dt.updateElement();
dt.deleteElement();
dt.saveXML("src/com/bf/javacore/new_phone.xml");
}
}
- DOM4J: SAXReaer
- require dom4j.jar file (dom4j-1.6.1.jar) put files under new lib folder : Referenced Libraries: add build path: add external Jar
- dom4j-1.6.1.jar
- Jaxen 1.1 beta-6
- Read with SAXReader
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4JTest {
public static void main(String[] args) {
try {
// use SAXReader to read file int a document
SAXReader sr = new SAXReader();
Document doc = sr.read(new File("src/com/bf/javacore/new_phone.xml"));
System.out.println(doc);
// get root
Element e = (Element) doc.getRootElement();
System.out.println(e.getName());
System.out.println(e.getText());
// get elements as a list and print
List<Element> list = e.elements();
for (Element el : list) {
System.out.println(el.getName());
System.out.println("\t"+el.attributeValue("name"));
List<Element> typeE = el.elements();
for(Element el2: typeE){
System.out.println(el2.getName());
System.out.println("\t"+el2.attributeValue("name"));
}
System.out.println("_ _ _ _ _ _ _ _ _ _ ");
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
- Dom4j: XMLWriter
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4JTest3 {
Document doc=null;
public Dom4JTest3(){ //initialize & read
try {
SAXReader sr= new SAXReader();
doc=sr.read(new File("src/com/bf/javacore/new_phone2.xml"));
} catch (DocumentException e) {
e.printStackTrace();
}
}
public void add(String path){ //add
Element root= doc.getRootElement();
Element brand=root.addElement("Brand");
brand.addAttribute("namd","Sony");
Element type= brand.addElement("Type");
type.addAttribute("name","Xperia");
Element type2= brand.addElement("Type");
type2.addAttribute("name","XperiaZ");
saveXML(path);
}
//update
public void update(String path){
Element root=doc.getRootElement();
List<Element> list=root.elements();
int i=1;
for(Element e: list){
e.addAttribute("id", " "+i);
i++;
}
saveXML(path);
}
//delete
public void delete(String path){
Element root=doc.getRootElement();
List<Element> childList=root.elements();
for(Element el: childList){
if("Huawei".equals(el.attributeValue("name"))){
root.remove(el);
}
}
saveXML(path);
}
//save XML
public void saveXML(String path){
try {
XMLWriter writer=new XMLWriter(new FileOutputStream(path),
OutputFormat.createPrettyPrint());
writer.write(doc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//main
public static void main(String[] args) {
Dom4JTest3 dt= new Dom4JTest3();
dt.add("src/com/bf/javacore/new_phone3.xml");
dt.update("src/com/bf/javacore/new_phone3.xml");
dt.delete("src/com/bf/javacore/new_phone3.xml");
dt.saveXML("src/com/bf/javacore/new_phone3.xml");
}
}
- XPATH: public List selectNodes(Object context, XPath sortXPath)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4JTest4 {
Document doc = null;
public Dom4JTest4() { // initialize & read
try {
SAXReader sr = new SAXReader();
doc = sr.read(new File("src/com/bf/javacore/new_phone2.xml"));
} catch (DocumentException e) {
e.printStackTrace();
}
}
// delete by Xpath
public void deleteByXPath(String path) {
Element root = doc.getRootElement();
// if "/" is included in xpath, then start from Root
List<Element> childList = root.selectNodes("Brand[@name='Huawei']");
for (Element e : childList) {
System.out.println(e.getName() + " " + e.attributeValue("name"));
root.remove(e);
// if ("Huawei".equals(e.attributeValue("Brand", "name")))
// e.getParent().remove(e);
}
saveXML(path);
}
// save XML
public void saveXML(String path) {
try {
XMLWriter writer = new XMLWriter(new FileOutputStream(path), OutputFormat.createPrettyPrint());
writer.write(doc);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// main
public static void main(String[] args) {
Dom4JTest4 dt = new Dom4JTest4();
dt.deleteByXPath("src/com/bf/javacore/new_phone4.xml");
dt.saveXML("src/com/bf/javacore/new_phone4.xml");
}
}