顯示具有 Java SE 標籤的文章。 顯示所有文章
顯示具有 Java SE 標籤的文章。 顯示所有文章

2021年3月21日 星期日

Eclipse 安裝與設定 for CentOS 8

目標設定
  • 在 CentOS 8 linux 中安裝 Eclipse

Eclipse 安裝流程
  1. 下載套件
  2. 將檔案解壓縮至 /opt 目錄下
    $ tar zxvf eclipse-inst-jre-linux64.tar.gz -C /opt/
    $ cd /opt/eclipse-installer
    
  3. 執行安裝工作:
    $ ./eclipse-inst
    
    • 選擇安裝項目:
    • 指定工作目錄後,進行安裝工作
    • 同意授權!
    • 安裝流程
    • 安裝結束,可直接啟動!
  4. 啟動時,選擇工作目錄
  5. 出現歡迎畫面!
  6. 操作畫面

2021年2月26日 星期五

VSCode 基本安裝與 Java 套件的使用

VSCode 安裝
  1. 下載網址:
  2. 執行安裝工作!
    • Windows 10:點擊下域的檔案,即可執行安裝工作,可一鍵執行完成!
    • CentOS 8:按照說明文件內容,使用 yum 進行安裝即可!

VSCode 設定
  1. 開啟 VSCode
  2. 執行 Extensions
  3. 輸入 Java
  4. 選擇 Java Extension Pack 後,按下 install 按鍵:
    這個套件一口氣會協助安裝六個套件:
    • Visual Studio IntelliCode
    • Language Support for Java(TM) by Red Hat
    • Debugger for Java
    • Java Test Runner
    • Maven for Java
    • Project Manager for Java
  5. 直接使用瀏覽器查看!
建立 Java SE project
  1. 使用 Ctrl+Alt+p 開啟命令列!
  2.  
  3. 輸入並選擇 Java: Create Java Project...
  4. 選擇 No build tools 項目
  5. 選擇存放專案的資料夾
  6. 輸入專案名稱
  7. 查看專案內容
  8. 如果沒有安裝 JDK 或是 OpenJDK ,可以利用此時進行安裝的工作:
  9. 按下「Get the Java Development Kit」按鍵,將連至 Red Hat Developer 官方網站
  10. 若是 Windows 10 的使用者,可在 Red Hat Developer 網站中,下載 OpenJDK 相關套件,並且安裝!
  11. CentOS 8 的使用者,可以利用 yum 進行安裝工作:
    # yum install java-latest-openjdk java-latest-openjdk-devel
    # alternatives --config java
    (選擇java-latest-openjdk.x86_64)
    # javac --version
    
  12. 選擇視窗左下角的 Manager 項目:
  13. 選擇 setting 項目:
  14. 輸入 java.runtime 找出 Java>Configuration:Runtimes 項目,進行 settings.json 檔案的編輯:
  15. 輸入下列資料,並且存檔:
  16. 切換回 setting 項目,選擇 Workspace 選項,輸入 java.home 關鍵字後,編輯 Java:Home 的 settings.jason 檔案:
  17. 編寫內容如下:
  18. 重新執行專案,分別按下右上的兩個按鍵,查看結果:

建立 Java EE project
  1. 安裝 Apache Tomcat 9,CentOS 8 可參考這一篇!Windows 10 可參考這一篇!
  2. 在工作目錄/專案目錄底下,找到 .classpath 檔案,加入下列設定:
      <classpathentry kind="lib" path="/opt/tomcat/apache-tomcat-9.0.44/lib/servlet-api.jar"/>
    
  3. 重新啟動 vscode 測試!

相關資料索引
參考文獻:
  1. 使用 VSCode 進行 Java SE/EE 開發

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

2015年9月30日 星期三

Comparator 的用法

Comparator 的用法:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorDemo {
    public static void main(String[] args){
    
        List<Student> studentList = new ArrayList<>(3);
        Comparator<Student> sortName = new StudentSortName();
        Comparator<Student> sortGpa = new StudentSortGpa();
        
        studentList.add(new Student("Thomas Jefferson", 1111, 3.8));
        studentList.add(new Student("John Adams", 2222, 3.9));
        studentList.add(new Student("George Washington", 3333, 3.4));
        
        Collections.sort(studentList, sortName);
        for (Student student : studentList){
            System.out.println(student.getName());
        }
         Collections.sort(studentList, sortGpa);
        for (Student student : studentList){
            System.out.println(student.getGpa());
        }
    }
}

public class Student {
private String name;
    private long id = 0;
    private double gpa = 0;
            
    public Student(String name, long id, double gpa) {
        this.name = name;
        this.id = id;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }

    public double getGpa() {
        return gpa;
    }
}

import java.util.Comparator;

public class StudentSortName implements Comparator<Student> {

    public StudentSortName() {
    }

    @Override
    public int compare(Student o1, Student o2) {
        int result = o1.getName().compareTo(o2.getName());
        if (result != 0){return result;}
        else { return 0;}
    }
}

import java.util.Comparator;

public class StudentSortGpa implements Comparator<Student> {

    public StudentSortGpa() {
    }

    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getGpa() < o2.getGpa()){return 1;}
        else if (o1.getGpa() > o2.getGpa()){ return -1;}
        else {return 0;}
    }
}

Comparable 的用法

Comparable 的用法:
public class ComparableStudent implements Comparable<ComparableStudent>{
    private String name;
    private long id = 0;
    private double gpa = 0.0;

    public ComparableStudent(String name, long id, double gpa) {
        this.name = name;
        this.id = id;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }
        
    @Override
    public int compareTo(ComparableStudent o) {
        int result = this.name.compareTo(o.getName());
        if (result > 0){return 1;}
        else if (result < 0){return -1;}
        else {return 0;}
    }
}

Demo 程式:
import java.util.Set;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args){
        Set<ComparableStudent> studentList = new TreeSet<>();
        
        studentList.add(new ComparableStudent("Thomas Jefferson", 1111, 3.8));
        studentList.add(new ComparableStudent("John Adams", 2222, 3.9));
        studentList.add(new ComparableStudent("George Washington", 3333, 3.4));
         
         for (ComparableStudent student : studentList){
             System.out.println(student.getName());
         }
    }
}

Queue 的應用


import java.util.ArrayDeque;
import java.util.Deque;

public class NewClass {
    public static void main(String[] args){
    
        Deque<String> stack = new ArrayDeque<>();
        stack.push("One");
        stack.push("Two");
        stack.push("Three");
        
        int size = stack.size() -1;
        while(size >= 0){
            System.out.println(stack.pop());
        }
    }
}

Map 應用


import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapDemo {
    public static void main(String[] args){
    
        Map<String, String> shirtList = new TreeMap<>();
        shirtList.put("S001", "Blue Shirt");
        shirtList.put("S002", "Black Shirt");
        shirtList.put("S003", "Gray Shirt");
        
        Set<String> keys = shirtList.keySet();
        System.out.println("====== Shirt List ======");
        for (String key : keys){
            System.out.println("Part#: " + key + " " 
                               + shirtList.get(key));
        } 
    }
}

Set 應用

某家公司的面試題目:
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;

public class SetDemo {
    public static void main(String[] args){
    
        Set<Integer> num = new TreeSet<>();
        Scanner scanner = new Scanner(System.in);
        Integer[] b = new Integer[3];
        for (int i = 0; i < 3 ;  i++){
            System.out.print("Please the eage's length: ");
            num.add(scanner.nextInt());
        }
        num.toArray(b);
        if (b[2] < (b[0]+b[1])){
        switch (num.size()){
            case 1: 
                System.out.println("正三角形");
                break;
            case 2:
                System.out.println("等腰三角形");
                break;
            case 3:
                if (triangle(b)){
                    System.out.println("直角三角形");
                } else {
                    System.out.println("其他種類三角形");
                }
        }
        } else {
             System.out.println("無法構成三角形");
        }
    }

    private static boolean triangle(Integer[] b) {
        if ((b[2] * b[2]) == (b[0]*b[0] + b[1]*b[1])){
          return true;
        } else {
            return false;
        }
    }
}


2015年9月23日 星期三

Boxing & UnBoxing

AutoBoxing 與 Auto Unboxing:
public class AutoBox {
    public static void main(String[] args){
    
        Integer intObject = new Integer(1);
        int intPrimitive = 2;
        
        Integer tempInteger;
        int tempPrimitive;
        
        tempInteger = new Integer(intPrimitive);
        tempPrimitive = intObject.intValue();
        
        tempInteger = intPrimitive;  //Auto Boxing
        tempPrimitive = intObject; // Auto Unboxing
    }
}

收集器:ArrayList & List

Collection 利用 Generic 來實作的好處:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
    public static void main(String[] args){
    
        List partList = new ArrayList<>();
        partList.add(new Integer(1111));
        partList.add(new Integer(2222));
        partList.add(new Integer(3333));
        partList.add("Hello World");  //Compile Error : Not Integer
        
        // 利用 Iterator 來遍訪 ArrayList 內的 elements 
        Iterator elements = partList.iterator();  
        while (elements.hasNext()){
            Integer partNumberObject = elements.next();
            int partNumber = partNumberObject.intValue();
            
            System.out.println("Part Number: " + partNumber);
        }
    }
}