2015年10月12日 星期一

Java 的 Thread 基本應用

繼承 Thread :
public class ExampleThread extends Thread{
    @Override
    public void run() {
        for(int i = 0; i<100; i++){
            System.out.println("i: " + i);
        }
    }
}

public class Demo {
    public static void main(String[] args){
        ExampleThread t1 = new ExampleThread();
        t1.start();
    }
}

執行 Runnable 介面 :
public class ExampleRunnable implements Runnable{

    @Override
    public void run() {
        for(int i = 0; i<100; i++){
            System.out.println("i: " + i);
        }
    }  
}

public class RunnableDemo {
     public static void main(String[] args){
        ExampleRunnable r1 = new ExampleRunnable();
        Thread t1 = new Thread(r1);
        t1.start();
    }
}

Java 檔案管理程式

NIO.2 基本應用:
import java.nio.file.Path;
import java.nio.file.Paths;

public class NIODemo {
    public static void main(String[] args){
        Path p1 = Paths.get("C:\\workspace\\test\\test1\\hello.text");
        System.out.println("Get File Name: " + p1.getFileName());
        System.out.println("Get Parent: " + p1.getParent());
        System.out.println("Get Name Count: " + p1.getNameCount());
        System.out.println("Get Root:" + p1.getRoot());
        System.out.println("Is Absolute:" + p1.isAbsolute());
        System.out.println("To Absolute Path:" + p1.toAbsolutePath());
        System.out.println("To URI Path:" + p1.toUri());
    }
}

Serializable 的應用

範例:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class Stock implements Serializable{
    private static final long serialVersionUID = 100L;
    private String symbol;
    private int shares;
    private double purchasePrice;
    private transient double currPrice;

    public Stock(String symbol, int shares, double purchasePrice) {
        this.symbol = symbol;
        this.shares = shares;
        this.purchasePrice = purchasePrice;
        setStockPrice();
    }
    
    private void setStockPrice() {
        this.currPrice = this.purchasePrice;
    }
     
    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException{
        ois.defaultReadObject();
        setStockPrice();
    }
}

import java.io.FileInputStream;
import java.io.Serializable;
import java.util.Set;

public class Portfolio implements Serializable{
    public transient FileInputStream inputFile;
    public static int BASE = 100;
    private transient int totalValue = 10;
    private Set stocks;
 
    Portfolio(Stock s1, Stock s2, Stock s3) {
        this.stocks.add(s1);
        this.stocks.add(s2);
        this.stocks.add(s3);
    }  
}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Demo {
    public static void main(String[] args){
    
        Stock s1 = new Stock("ORCL",100, 32.5);
        Stock s2 = new Stock("AOOL",100, 245);
        Stock s3 = new Stock("GOGL",100, 54.67);
        
        Portfolio p = new Portfolio(s1,s2,s3);
        
        try(FileOutputStream fos = new FileOutputStream(args[0]);
            ObjectOutputStream out = new ObjectOutputStream(fos)){
            out.writeObject(p);
        } catch (IOException ex) {
           System.out.println("Exception writing out Portfolio :" + ex);
        }
        
        try(FileInputStream fis = new FileInputStream(args[0]);
            ObjectInputStream in = new ObjectInputStream(fis)){
            Portfolio newP = (Portfolio)in.readObject();
        } catch (ClassNotFoundException | IOException ex) {
           System.out.println("Exception reading in Portfolio :" + ex);
        }
    }
}

2015年10月7日 星期三

I/O Chain 的練習

Buffer 與 File 的 Chain :
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 ChainDemo {
    public static void main(String[] args){
        try(BufferedReader bufInput = new BufferedReader(new FileReader(args[0]));
            BufferedWriter bufOutput = new BufferedWriter(new FileWriter(args[1]))){
            String line = "";
            while ((line = bufInput.readLine()) != null){
                bufOutput.write(line);
                bufOutput.newLine();
            }
        }   catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        } catch (IOException ex) {
            System.out.println("I/O Error");
        }  
    }
}

InputStream 與 OutputStream

Byte 種類的 I/O 處理:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class StreamDemo {
    public static void main(String[] args){
        byte[] data = new byte[128];
        int dataLen = data.length;
        
        try(FileInputStream fis = new FileInputStream(args[0]);
            FileOutputStream fos = new FileOutputStream(args[1])){
            System.out.println("Bytes available: " + fis.available());
            int count = 0;
            int read = 0;
            while ((read = fis.read(data)) != -1){
                if (read < dataLen) 
                    fos.write(data,0,read);
                else
                    fos.write(data);
                count += read;
            }
            System.out.println("Wrote: " + count);
        }   catch (FileNotFoundException ex) {
            System.out.println("File not Found! " + ex);
        } catch (IOException ex) {
            System.out.println("I/O Error! " + ex);
        }
    }
}

Assertion 用法


import java.util.Scanner;

public class Demo {
    public static void main(String[] args){
    
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please input positive number:");
        int input = scanner.nextInt();
        if (input > 0){
            System.out.println("Number: " + input);
        } else {
            assert (input > 0): "執行有誤....";
            System.out.println("Error : " + input);
        }
    }
}

Java 例外處理--AutoCloseable

有 catch 敘述:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class OpenFileDemo{
  public static void main(String[] args){
    System.out.println("About to open a file...");
    
    try (InputStream in = new FileInputStream("hello.txt")){
      System.out.println("File is opened..");
      int data = in.read();
    } catch (FileNotFoundException e){
        System.out.println(e.getMessage());
    } catch (IOException e){
        System.out.println(e.getMessage());
    }
  }
}

沒有 catch 敘述(利用 throws,丟給上頭去傷腦筋...)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ThrowDemo {
    public static void main(String[] args){
        try {    
            int data = readByteFromFile();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    private static int readByteFromFile() throws FileNotFoundException, IOException {
        try(InputStream in = new FileInputStream("a.txt")){
            System.out.println("File is opening...");
            return in.read();
        }
    }
}

2015年10月2日 星期五

正規化表示式

Pattern & Matcher 的應用:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegxDemo {
    public static void main(String[] args){
    
        String test = "He was a teacher";
        
        Pattern p1 = Pattern.compile("w.s");
        Matcher m1 = p1.matcher(test);
        if (m1.find()){
            System.out.println("Found: " + m1.group());
        }
        
        Pattern p2 = Pattern.compile("w[abc]s");
        Matcher m2 = p2.matcher(test);
        if (m2.find()){
            System.out.println("Found: " + m2.group());
        }
        
        Pattern p3 = Pattern.compile("t[^xyz]acher");
        Matcher m3 = p3.matcher(test);
        if (m3.find()){
            System.out.println("Found: " + m3.group());
        }

        String header = "<h1>Hello World<h1>";
        Pattern p4 = Pattern.compile("h1");
        Matcher m4 = p4.matcher(header);
        if (m4.find()){
            System.out.println("Found: " + m4.group());
            header = m4.replaceAll("p");
            System.out.println(header);
        }  

    }
}

Scanner 切割字串的應用


import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args){
        StringBuilder sb = new StringBuilder(64);
        String test = "1.1, 2.2, 3.3";
        float fsum = 0.0f;
        
        Scanner s = new Scanner(test).useDelimiter(", ");
        while(s.hasNextFloat()){
            float f = s.nextFloat();
            fsum += f;
            sb.append(f).append(" ");
        }
        System.out.println("Values for: " + sb.toString());
        System.out.println("FSum: " + fsum);
    }
}

StringBuilder 用法


import java.io.PrintWriter;
import java.util.StringTokenizer;

public class StringDemo {
    public static void main(String[] args){
        
        //StringBuilder 範例
        StringBuilder sb = new StringBuilder(500);
        
        sb.append(", this is a good day!");
        sb.insert(0,"Today is Friday!");
        for (int i = 1; i< 11 ; i++){
            sb.append(i).append("    ");
        }
        sb.append("] times");
        System.out.println(sb.toString());
        System.out.println();
        
        //String Methods 範例
        PrintWriter pw = new PrintWriter(System.out, true);
        String tc01 = "It was the best of times";
        String tc02 = "It was the worst of times";
        
        if (tc01.equals(tc02)){
            pw.println("Strings match...");
        }
        if (tc01.contains("It was")){
            pw.println("It was found");
        }
        String temp = tc02.replace("w", "zw");
        pw.println(temp);
        pw.println(tc02.substring(5, 12));
         pw.println();
         
        //String Split 範例
        String shirts = "Blue Shirt, Red Shirt, Black Shirt, Maroon Shirt";
        
        String[] results = shirts.split(", ");
        for (String shirtStr:results){
            pw.println(shirtStr);
        }
         pw.println();
         
        //Tokenizer 範例
        StringTokenizer st = new StringTokenizer(shirts, ", ");
        while(st.hasMoreTokens()){
            pw.println(st.nextToken());
        }
    }
}

Properties 的使用


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class Demo1 {
    public static void main(String[] args) throws FileNotFoundException{
    
        Properties myProps = new Properties();
        try{
            FileInputStream fis = new FileInputStream("C:\\ServerInfo.properties");
            myProps.load(fis);
        } catch (IOException e){
            System.out.println("Error: " + e.getMessage());
        }
        
        System.out.println("Server: " + myProps.getProperty("hostName"));
        System.out.println("User: " + myProps.getProperty("userName"));
        System.out.println("Password: " + myProps.getProperty("password"));
           
    }
}

Properties 的檔案內容:
hostName=www.example.com
userName=user
password=pass