總網頁瀏覽量

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

2013年8月15日 星期四

Android(java) 使用cmd

Android中,透過APK直接使用cmd指令與device溝通

private Process process = null;

String[] cmd1 = { "/system/bin/sh", "-c", "echo hello > /data/temp.txt"};
process = Runtime.getRuntime().exec(cmd1);

String[] cmd2 = { "/system/bin/sh", "-c", "echo hello > /data/temp.txt"};

process = Runtime.getRuntime().exec(cmd2);

2012年10月9日 星期二

Java 搜尋文字檔關鍵字並輸出

搜尋同一目錄內文字檔關鍵字後,並輸出整理到一個文字檔
可編譯為jar檔,重複使用

Source code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;


public class FindKeyWord {
    public static void main(String args[]) throws IOException{
        ReadClass mReadClass = new ReadClass();
        mReadClass.readData();
    }
}

class ReadClass{
    int count = 0;

    public void readData(){
        //String dirPath = "C:\\Users\\Test\\Desktop\\";
        String dirPathTemp = System.getProperty("user.dir");
        String dirPath = Matcher.quoteReplacement(dirPathTemp);
        CharSequence findWord = "keyword";
        File dir = new File(dirPath);
        StringBuilder sb = new StringBuilder();
        
        if(dir.exists() && dir.isDirectory()){
            String[] names = dir.list();
            for(String name: names){
                FileReader fr;
                try {
                    fr = new FileReader(dirPath + "\\"  + name);
                    BufferedReader bf = new BufferedReader(fr);
                    String data = null;
                    try {
                        while((data = bf.readLine()) != null){
                            if(data.contains(findWord)){
                                String regString = "=";
                                String[] StringArray = data.split(regString);
                                output(StringArray[1], dirPath);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        bf.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } 
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }               
            }
        }else{
            String info = "路徑錯誤: " +  dirPath + "請重新輸入";
        }
    }
    public void output(String str, String dirPath) throws IOException{
        String filePath = dirPath + "\\" + "data.txt"; 
        FileWriter mFileWriter = new FileWriter(filePath, true);
        String item = null;
        if((count/10) < 1){
            item = "  " + Integer.toString(count);
        }else if((count/10) < 10){
            item = " " + Integer.toString(count);
        }else{
            item = Integer.toString(count);
        }
        String mString = new String(item + ", keyword = " + str + "\r\n");
        mFileWriter.write(mString);
        mFileWriter.flush();
        mFileWriter.close();
        count++;
    }
}

2012年9月4日 星期二

JAVA常遇到疑問

3-2.6 == 0.4  =>為false
因為java使用基底型別進行浮點數計算時, 會不準確
3-2.6 為0.3999999999999

使用BigDecimal進行浮點數運算來解決

BigDecimal x = new BigDecimal("3");
BigDecimal x = new BigDecimal("2.6");
BigDecimal z = z.subtract(y);
double value = z.doubleValue();
System.out.println(value == 0.4);

                                                                                                                     

9/2 = 4
9/2.0 = 4.5
整數與浮點數的運算會轉為浮點數型態再進行運算

                                                                                                                     

使用Label與break

public static void main(String[] args){
    label:
        for(int i= 1; i <= 7; i++){
           System.out.print("TEST");
           if(i =  3)
                break label;
       }
}

當i = 3時, 就會跳出label, 使用雙重迴圈也是一樣的情形


java
clone()方法複製物件
當已經存在一個A物件,現在需要一個與A物件完全相同的B物件,並對B物件的屬性值進行修改,但是A物件原有的屬性值不能改變

使用Object類別中的clone()方法,可以用來完成物件的淺複製,即被複製的物件各個屬性都是基本型態,而不是參考型態的屬性(Example)






















JNI 記錄

Java call C

Step 1: Write the Java Code
建立HelloWorld.java
//HelloWorld.java
public class HelloWorld
{
    public native void showHelloWorld();
    static {
        System.loadLibrary("hello");//呼叫libhello.so
    }
                public static void main(String[] args){
                                new HelloWorld().showHelloWorld();
                }
}

Step 2: Compile the Java Code
執行javac HelloWorld.java //編譯

Step 3: Create the .h File (
這是自動產生出的不要去編輯)
javah -jni HelloWorld //自動產生對應C標頭檔,內容中粗體為C的函式宣告:
-d選項可以指定輸出路徑
-jni 表示產生jni標頭檔案

//hello.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    showHelloWorld
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_showHelloWorld
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

Step 4: Write the Native Method Implementation
建立jni.c

//hello.c
#include <jni.h>
#include "HelloWorld.h"
#include <stdio.h>

JNIEXPORT void JNICALL
Java_HelloWorld_showHelloworld(JNIEnv *env, jobject obj)
{
                printf("Hello world!\n");
                return;
}


Step 5: Create a Shared Library
執行
gcc -fPIC -shared -Ijni.h 目錄> -Ijni_md.h目錄> jni.c -o libjni.so




C call Java
C訪問java不能透過函數指標 只能透過通用的參數介面
需要把想要訪問的類別名 函數名稱 參數傳遞給java引擎

訪問Java中函數的流程:

1. 取得Java對象的類別
cls = env -> GetObjectClass(jobject)

2. 取得Java函數的id
jmethodId mid = env -> GetMethodId(cls, "method_name", "([Ljava/lang/String;)V");

第二個參數為Java中的函數名稱
第三個參數為Java函數的參數和返回值

Java提供javap工具 可以查看Java函數的輸入 返回參數
javap -s com/android/HelloWorld

-s的含義是簽名(Signature) 因為Java允許函數重載 所以不同的參數 返回值代表著不同的函數

3. 找到函數後 就可以使用該函數
env -> CallXXXMethod(jobject, mid, ret);

訪問Java中變數的流程:

1. cls = env -> GetObjectClass(jobject)

取得變數的id
2. jfieldId fid = env -> GetFiledId(cls, "filed_name", "I");

field_nameJava變數的名稱
第三個參數為變數的類型

3. 取得變數值
value = env -> GetXXXField(env, jobject, fid)





JNIEnv 表示Java環境, jobject 指向呼叫的物件
java: int, long, byte, boolean, char, short, float, double, object
c中表示類型前面加一個j來表示

jclass取得:   
jclass FindClass(const char*, clsName);
jclass GetObjectClass(jobject obj);
jclass GetSuperClass(jclass obj);

jclass cls_string = env -> FindClass("java/lang/String") 取得string類型方式

取得方法名:
GetFieldID/GetMethodID
GetStaticFieldID/GetStaticMethodID

Java類型
native類型
boolean
Z
byte
B
char
C
double
D
float
F
int
I
long
L
Object
‘L’+’package’+’;’
short
S

object ---> Ljava/lang/Sting;
Array ---> [Ljava/lang/object;



























2012年9月2日 星期日

Java版本 處理字幕檔

由於 java對中文的編碼有不同的格式, 處理字幕檔有些麻煩, 需先判斷編碼內容, 再去做處理, 輸出也不好處理, 最好找到一樣格式的srt檔案, 否則要先轉檔後再做擷取會比較好實作

程式內容:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class Subtitle {
    public static void main(String []args)throws IOException{
        GetSubtitle mGetSubtitle = new GetSubtitle();
        mGetSubtitle.startOperation();
        mGetSubtitle.stopOperation();
    }
}

class GetSubtitle{
    public File fileEng;


        
    public File fileCht;
    public InputStreamReader readEng;
    public InputStreamReader readCht;
    
    public BufferedReader brEng;
    public BufferedReader brCht;
    public StringBuilder sbEng;
    public StringBuilder sbCht;
    public String strEng, strCht;
    
    GetSubtitle() throws IOException{
        initial();
    }

    public void initial() throws IOException{
        fileEng = new File("C:\\Documents and Settings\\kent\\eclipse_work\\Subtitle\\Mission.Impossible_eng.txt");
        fileCht = new File("C:\\Documents and Settings\\kent\\eclipse_work\\Subtitle\\Mission.Impossible_cht.txt");
        readEng = new InputStreamReader (new FileInputStream(fileEng),"utf-8");
        brEng = new BufferedReader(readEng);
    }
    
    public void startOperation() throws IOException{
        while((strEng = brEng.readLine()) != null ){
            if(strEng.contains(":")){
                repeatReadCht();
            }
        }
    }
    public void repeatReadCht() throws IOException{
        readCht = new InputStreamReader (new FileInputStream(fileCht),"utf-8");
        brCht = new BufferedReader(readCht);
        while((strCht = brCht.readLine()) != null){
            if(strEng.equals(strCht)){
                outputData();
                break;
            }
        }
    }
    public void outputData() throws IOException{
        while(strEng.length() != 0){
            if((strEng = brEng.readLine()) != null){
                System.out.print(strEng + " ");
            }else{
                break;
            }
        }
        System.out.print("\r\n");
        while(strCht.length() != 0 ){
            if((strCht = brCht.readLine()) != null){
                System.out.println(strCht);
            }else{
                break;
            }
        }
    }
    
    public void stopOperation() throws IOException{
        brEng.close();
        brCht.close();
    }
}




網路上判斷編碼的方法:

class Convert{
    Convert(){  
    }
    public String convertCodeAndGetText() {
        File file = new File("C:\\Documents and Settings\\kent\\eclipse_work\\Subtitle\\Avengers_cht.txt");
        BufferedReader reader;
        String text = "";
        try{
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream in = new BufferedInputStream(fis);
        in.mark(4);
        byte[] first3bytes = new byte[3];
        in.read(first3bytes);//找到文字檔的前三個字節並自動判斷文字檔類型
        in.reset();
        if(first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB && first3bytes[2] == (byte) 0xBF) {// utf-8
            reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            System.out.println("utf-8");
        }else if(first3bytes[0] == (byte) 0xFF && first3bytes[1] == (byte) 0xFE) {
            reader = new BufferedReader(new InputStreamReader(in, "unicode"));
            System.out.println("unicode");
        }else if(first3bytes[0] == (byte) 0xFE && first3bytes[1] == (byte) 0xFF) {
            reader = new BufferedReader(new InputStreamReader(in,"utf-16be"));
            System.out.println("utf-16be");
        }else if(first3bytes[0] == (byte) 0xFF && first3bytes[1] == (byte) 0xFF) {
            reader = new BufferedReader(new InputStreamReader(in, "utf-16le"));
            System.out.println("utf-16le");
        }else{
            reader = new BufferedReader(new InputStreamReader(in, "GBK"));
            System.out.println("GBK");
        }
        String str = reader.readLine();
        while(str != null){
            text = text + str + "\n";
            str = reader.readLine();
        }
        reader.close();
        }catch(FileNotFoundException e) {
        e.printStackTrace();
        }catch(IOException e) {
                e.printStackTrace();
        }
        return text;
    }
}

2012年5月24日 星期四

JAVA 正則表示式


正則表達式: 符合一定規則的表達式
用於專門操作字串,用一些特定的符號來表示一些代碼操作,簡化程式碼
//對號碼進行校驗
//長度5~15, 0不可第一位, 只可數字
class Hello{

    public static void main(String[] args){

       String num = "123448940";

       int len = num.length();

       if(len >= 5 && len <= 15){

           if(!num.startsWith("0")){

              char[] arr = num.toCharArray();

              boolean flag = true;

              for(int x = 0; x < arr.length; x++){

                  if(!(arr[x] >= '0' && arr[x] <= '9')){

                     flag = false;

                     break;

                  }

              }

              if(flag){

                  System.out.println("num: " + num);

              }else{

                  System.out.println("請輸入數字");

              }

           }else{

              System.out.println("不可0開頭");

           }

       }else{

           System.out.println("長度不符");

       }

    }

}

改良:
//對號碼進行校驗
//長度5~15, 0不可第一位, 只可數字
class Hello{

    public static void main(String[] args){   

       checkNum();

    }

    public static void checkNum(){

       String num = "151651651";

       //規則 第一位[1-9], 第二位以後[0-9] 出現次數{4,14}

       String regex = "[1-9][0-9]{4,14}";

       boolean flag = num.matches(regex);

       if(flag){

           System.out.println("OK");

       }else{

           System.out.println("No");

       }

    }

}


操作功能
1.  匹配: String matches方法
[bcd] 第一個字元只能是b, c, d,並且只能有一個字元
[a-zA-Z][0-9] 第一位為字母,第二位為數字
[^abc]第一位不可a, b, c
[a-c[e-g]] aceg
[a-g&&[b-d]] b,c,d 交集

\d 也可以表示輸入為[0-9],使用時要注意特殊符號
\D 表示[^0-9]
\s 表示空白字元
\S表示非空白字元
\w 表示數字或英文字

\W表示非數字或非英文字

public class Main{

    public static void main(String[] args){

       demo();

    }

    public static void demo(){

       String str = "b5";

       String reg = "[bcd][\\d]";

       boolean b = str.matches(reg);

       System.out.println(b);//ture

    }

}

Greedy
X?:  X值出現一次或零次(完全沒有, 空字元)
X*:  X值出現零次或多次
X+:  X值出現一次或多次
X{n}:  X恰好n
X{n, }: X至少n
X{n,m}:X至少n次,但不超過m

    public static void testString(){
    String a = "11 2";
    String b = "2";
    String c = "22";
    String reg1 = "2?";
    p(a.matches(reg1));//false
    p(b.matches(reg1));//true
    p(c.matches(reg1));//false
   
    String reg2 = "2*";
    p(a.matches(reg2));//false
    p(b.matches(reg2));//true
    p(c.matches(reg2));//true

    String reg3 = "2+";
    p(a.matches(reg3));//false
    p(b.matches(reg3));//true
    p(c.matches(reg3));//true
   
    String reg4 = "2{1}";
    p(a.matches(reg4));//false
    p(b.matches(reg4));//true
    p(c.matches(reg4));//false
    }


2.  切割 split
public class Main{

    public static void main(String[] args){

       demo();

    }

    public static void demo(){

       String str = "a,b,c,d,e,f";

       String reg = ",";

       String[] strArray = str.split(reg);

       for(String s: strArray){

           System.out.println(s);

       }

    }

}

空格切割:
String str = "sqss   erfr    rferfer";
String reg = " +";  //空格出現一次或多次!

.切割
String str = "dwdaqwd.d.wd.wf.wqfq.wf";
String reg = "\\."; //.是特殊符號,必須先轉譯

特殊:
String str = "c:\\dwdqw\\dqda\\a.txt";
String reg = "\\\\";

特殊: 以疊字分割
String str = "daggegffftyvvvrs";
String reg = "(.)\\1+";
讓這個規則被蟲用,可以將規則封裝成一組,用()完成,組的出現會有編號,從1開始,想要使用已有的組可以通過 \n(n就是組的編號)的形式來獲取

3.替換 replaceAllreplace(String類別)
public class Main{

    public static void main(String[] args){

       demo();

    }

    public static void demo(){

       String str = "swdwdw46846232def48ce8f4";

       String reg = "\\d{5,}";//替換規則

       String newStr = "#";//替換為此字串

      

       String resultString = str.replaceAll(reg, newStr);

       System.out.println(resultString);

    }

}


將疊字換成單個字母 zzz -> z
String str = "swwwffrffevvvtthjyjyrrr";
String reg = "(.)\\1+";//替換規則
String newStr = "$1";//替換為此字串 $使用前一組的規則
String resultString = str.replaceAll(reg, newStr);

4.獲取:將字串中符合規則的子字串取出
將正則表達式封裝成物件
讓正則物件和要操作的字串相關聯
關聯後,獲取正則匹配引擎
通過引擎對符合規則的子字串進行操作,例如取出
class Hello{

    public static void main(String[] args){   

       demo();

    }

    public static void demo(){

       String str = "kab jio jeioj joijio skl";

       String reg = "\\b[a-z]{3}\\b";

       //將規則封裝成物件

       Pattern p = Pattern.compile(reg);

       //讓正則物件與要作用的字串相關聯

       Matcher m = p.matcher(str);

       //System.out.println(m.matches());

       //String類中的matches方法,即使用PatternMatcher類的matcher方法

       //只不過String方法封裝後, 使用較簡單, 但功能一致

      

       //將規則作用到字串上, 並進行符合規則的子串查找

       while(m.find()){

           System.out.print(m.group() + " ");//用於獲取匹配後結果

           //kab //jio  //skl

           System.out.println(m.start() + "..." + m.end());

           //0...3  //4...7  /21...24

       }

    }

}

1.  如果只想知道該字串是對或錯,使用匹配
2.  想要將已有的字串轉變成另一個字串,替換
3.  想要按照自定的方式將字串變成多個字串,切割。獲取規則外的子串
4.  想要拿到符合需求的字串中的子串,獲取。獲取符合規則的子串
class Hello{

    public static void main(String[] args){   

       demo();

    }

    public static void demo(){

       String str = "aaa..aa...ab...bb..bbb..ccc..cc.ddd...dd.d..ee";

       str = str.replaceAll("\\.+", "");

       System.out.println(str);//aaaaaabbbbbbcccccddddddee

       str = str.replaceAll("(.)\\1+", "$1");//去疊字

       System.out.println(str);//abcde

    }

}

檢查mail是否符合規則
class Hello{

    public static void main(String[] args){   

       checkMail();

    }

    public static void checkMail(){

       String mail = "abcdefg@google.com.te";

       String reg = "[a-zA-Z0-9_]{6,12}@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";

       System.out.println(mail.matches(reg));

    }

}