java学习笔记

1 开始使用

1.1 将java路径加到path变量

set path = (/tools/ctools/java/jdk1.8.0_131/bin $path)

1.2 编写HelloWorld程序

file HelloWorld.java

import java.util.* ;

public class HelloWorld { //注意, 这是个public class, 它所在的文件名必须是HelloWorld.java.
    public static void main(String[] args){
        System.out.println("HelloWorld.");
    }
}

1.3 编译和运行

$ javac HelloWorld.java  ;# 编译
$ java HelloWorld        ;# 运行
HelloWorld.

1.4 多个文件的编译与运行:

程序文件结构和程序内容

scr
|---smsg
|   \--Smsg.java
|       > package smsg; //注意这个地方, import本class时会用到
|       > public class Smsg{ ... }
|
|---sms_proc
|   |--SmsProc.java
|   |   > package sms_proc;
|   |   > import sms_proc.SmsProcReg; //通package name导入其它模块
|   |   > public class SmsProc{ ... }
|   |
|   \--SmsProcReg.java
|       > package sms_proc;
|       > public class SmsProcReg{ ... }
|    
|---sms_wrap
|   |--SmsWrap.java
|   |   > package sms_wrap;
|   |   > import sms_wrap.SmsWrapReg; //通package name导入其它模块
|   |   > public class SmsWrap{ ... }
|   |
|   \--SmsWrapReg.java
|       > package sms_wrap;
|       > public class SmsWrapReg{ ... }
|    
\---top
    \--Top.java
        > package top;
        > import smsg.Smsg;        //通package name导入其它模块
        > import sms_proc.SmsProc; //通package name导入其它模块
        > import sms_wrap.SmsWrap; //通package name导入其它模块
        > public class Top{
        >   public static main(String[] args){ ... }   
        > }
     

编译

# -d ../bin, 将编译后的class files放到目录../bin/目录.
# ../scr/*/*.java, 待编译的java程序文件.
javac -d ../bin ../scr/*/*.java

编译后文件的目录结构为:
bin
|---smsg
|   \---Smsg.class
|---sms_proc
|   |--SmsProc.class
|   \--SmsProcReg.class
|---sms_wrap
|   |--SmsWrap.class
|   \--SmsWrapReg.class
\---top
    \--Top.class

运行:

# -cp ../bin, 设置class search path(class path, 简称cp). <class search path of directories and zip/jar files>
java -cp ../bin top/Top | tee ../log/run.log

2 控制执行流程

2.1 if - else if - else

public class ex {
    public static void main(String[] args) {
        int x = 78;
        if (x>=90){
            System.out.println("A");
        } else if(x>=60){
            System.out.println("B");
        } else {
            System.out.println("C");
        }
    }
}

2.2 switch-case

public class ex {
    public static void main(String[] args) {
        int opt = 2;
        switch(opt){
            case 1:
                System.out.println("select 1");
                break; //注意需要有break语句, 不然会把switch中后续语句都执行了.
            case 2:
                System.out.println("select 2");
                break;
            case 3:
                System.out.println("select 3");
                break;
            default:
                System.out.println("select none");
                break;
        }
    }
}

switch语句选项还可以是字符串.

2.3 while

public class Main {
    public static void main(String[] args) {
        int sum = 0; // 累加的和,初始化为0
        int n = 1;
        while (n <= 100) { // 循环条件是n <= 100
            sum = sum + n; // 把n累加到sum中
            n ++; // n自身加1
        }
        System.out.println(sum); // 5050
    }
}

2.4 for

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i=1; i<=100; i++) {
            sum = sum + i;
        }
        System.out.println(sum);
    }
}
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int i=0; i<ns.length; i++) {
            System.out.println(ns[i]);
            i = i + 1;
        }
    }
}
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) { //类似于foreach
            System.out.println(n);
        }
    }
}

2.5 break和continue

break : 跳出当前循环, 也就是整个循环都不会执行了.
continue: 提前结束本次循环, 直接继续执行下次循环.

3. 数组

3.1 遍历

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int i=0; i<ns.length; i++) {
            int n = ns[i];
            System.out.println(n);
        }
    }
}
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

3.2 打印数组

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        System.out.println(ns); // [I@15bd9742, JVM中的引用地址
        System.out.println(Arrays.toString(ns)); // [1, 4, 9, 16, 25]
    }
}

3.3 排序

Arrays.sort(ns), 正序排序, 会修改数组本身
好像没有逆序的方法.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 28, 12, 89, 73, 65, 18, 96, 50, 8, 36 };
        Arrays.sort(ns);
        System.out.println(Arrays.toString(ns));
    }
}

3.4 二维数组/多维数组

二维数组

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int[][] ns = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11 }   //可以不等长
        };
        System.out.println(ns.length); // 3
    
        int[] arr0 = ns[0];
        System.out.println(arr0.length); // 4
        System.out.println(Arrays.toString(arr0)); // [1, 2, 3, 4]

        System.out.println(Arrays.toString(ns)); // [[I@xxxx, [I@xxxx, [I@xxxx]
        System.out.println(Arrays.deepToString(ns)); // [[1, 2, 3, 4], [5,6,7,8], [9,10,11]]
    }
}

三维数组

int[][][] ns = {
    {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    },
    {
        {10, 11},
        {12, 13}
    },
    {
        {14, 15, 16},
        {17, 18}
    }
};

3.5 main函数的参数是一个数组

public class Main {
    public static void main(String[] args) {
        for (String arg : args) {
            //if ("-version".equals(arg)) {
            if (arg.equals("-version")) {
                System.out.println("v 1.0");
                break;
            }
        }
    }
}

运行

$ javac Main.java
$ java Main -version
v 1.0

4 集合 collection

4.1 简介

标准库java.util包提供了三种类型的集合:
list: 有序列表集合.
set : 无重复元素的集合.
map : key-value映射表集合.

以下集合类是遗留类, 最好不使用:
Hashtable:
vector
stack

以下接口是遗留接口, 最好不使用:
Enumeration, 它被Iterator取代了.

4.2 list

list与数组类型, 不过对数组添加/删除元素时, 会非常不方便.
使用最多的是ArrayList.

List接口方法

接口方法 作用
booleen add (E e) 在末尾添加一个元素
booleen add (int index, E e) 在指定索引添加一个元素
booleen addAll(Collection c) 添加给定集合的所有元素
booleen addAll(int index, Collection c) 在指定索引添加给定集合的所有元素
E remove(int index) 删除指定索引的元素
boolean remove(Object e) 删除某个元素
E get(int index) 获取指定索引的元素
int size() 获取链表大小(元素的个数)
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Iterator;

public class ex {
    public static main(String[] args){
        List<String> l0 = new ArrayList<>();

        l0.add("apple");
        l0.add(null)   ; //允许添加空值null
        l0.add("pear") ;
        l0.add("apple");

        //在list初始化时赋初值
        List<String> l1 = new ArrayList<String>(){ //这个大括号相当于new接口
            { //这个大括号是构造代码块, 会在构造函数前调用
                System.out.println("在构造代码块中");
                this.add("element0"); //第〇个元素, this 可以省略.
                add("element1");      //第一个元素.
            }
        };

        System.out.println(l0.size()); //4

        String second = l0.get(1); //获取元素
        System.out.println(second); //null

        for(int i=0; i<l0.size(); i++){//使用idx遍历
            String s = l0.get(i);
            System.out.println(s);
        }

        for(Iterator<String> it=l0.iterator(); it.hasNext()){//使用it遍历
            String s = it.next();
            System.out.println(s);
        }

        for(String s: l0){//使用for each遍历
            System.out.println(s);
        }
    }
}

4.3 Map

import java.util.HashMap;
import java.util.Map;
public class Main {
    public static void main(String[] args) {
        Student s0 = new Student("Xiao Ming", 99);
        Student s1 = new Student("Xiao Hone", 88);

        Map<String, Student> m0 = new HashMap<>();
        Map<String, Student> m1 = new HashMap<>();

        m0.put(s0.name, s0); // 将"Xiao Ming"和Student实例映射并关联
        m0.put(s1.name, s1);

        m1.putAll(m0); //向map中添加另一个map的所有元素

        Student target = m0.get("Xiao Ming"); // 通过key查找并返回映射的Student实例
        System.out.println(target.name); // "Xiao Ming"
        System.out.println(target.score); // 99
        System.out.println(target == s0); // true,同一个实例

        Student another = m0.get("Bob");          // 查找另一个key
        System.out.println(another);              // 未找到返回null
        System.out.println(m0.containsKey("Bob)); // 判断是否存在key


        for(String k: m0.keySet()){ //使用for each遍历
            Student v = m0.get(k);
            System.out.println(k + " => " + v.score);
        }

        for(Map.Entry<String, Student> en: m0.entrySet()){ //使用entry遍历
            String  k = en.getKey();
            Student v = en.getValue();
            System.out.println(k + " => " + v.score);
        }
    }
}

class Student {
    public String name;
    public int score;
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
}

5. 读写文件

5.1 读取文件

import java.util.ArrayList  ;
import java.util.List       ;

import java.io.File         ;
import java.io.InputStream  ;
import java.io.Reader       ;
import java.io.BufferedReader   ;
import java.io.InputStreamReader;
import java.io.FileInputStream  ;
import java.io.FileNotFoundException  ;
import java.io.IOException  ;

public class EX {
    public static List<String> list_lines = new ArrayList<>();
    public static void main(String[] args){
        list_lines.addAll(readFileByLine("filename.txtx"));
    }

    public static List<String> readFileByLine(String filename){
        List<String> _lines = new ArrayList<>();

        File            file    = new File(filename);
        InputStream     is      = null;
        Reader          rd      = null;
        BufferedReader  bufrd   = null;

        try {
            //必须要try, 如果不用try包起来, 会报告:
            //"unreported exception EXCEP_NAME; must be caught or declared to be thrown."
            is      = new FileInputStream(file);
            rd      = new InputStreamReader(is);
            bufrd   = new BufferedReader(rd);

            String _line = null;
            while((_line=bufrd.readLine()) != null){
                _lines.add(_line);
            }
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                if(bufrd != null) { bufrd.close(); }
                if(rd    != null) { rd.close()   ; }
                if(is    != null) { is.close()   ; }
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        return _lines;
    }
}

5.2 写文件

public class EX {
    public static List<String> list_lines = new ArrayList<>();
    public static void main(String[] args){
        list_lines.add("1. abc");
        list_lines.add("2. defg");

        writeFileByFileWriter("out.txt");
    }

    public static void writeFileByFileWriter(String filename){
        File        file = new File(filename);
        FileWriter  fw   = null;

        try {
            if(!file.exists()){
                file.createNewFile();
            }
            fw = new FileWriter(file);

            for(String line: list_lines){
                fw.write(line + "\n");
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e){
                    e.printStackTree();
                }
            }
        }
    }
}

6 正则表达式

import java.util.regex.Matcher  ;
import java.util.regex.Pattern  ;

public class EX{
    public static void main(String [] args){
        String s0 = "1. abc defg";

        Pattern p = Pattern.compile("^\\s*(\\d+)\\s*\\.\\s*(\\w+)");
        Matcher m = p.matcher(s0);

        if (m.find()){
            String s1 = m.group(1);
            String s2 = m.group(2);

            System.out.println(s1 + " -> " + s2); // 1 -> abc
        }
    }
}

7 琐碎操作

7.1 字符串操作

int msb = Integer.valueOf("123").intValue(); #string转int
String sig = " A B C ".replaceAll("\\s+", ""); #替换掉str中的所有空格.

String s0 = "abcdEFG";
System.out.println(s0.length())     ; //7      , 获取字符串长度
System.out.println(s0.toUpperCase()); //ABCDEFG, 小写转为大写, 返回修改后的str, 不修改原str.
System.out.println(s0.toLowerCase()); //abcdefg, 大写转为小写, 返回修改后的str, 不修改原str.

7.2 文件判断

String filename = "../rpt/a.tcl";
File file = new File(filename);

file.exists()           ; // true , 文件是否存在
file.isDirectory()      ; // false, 是否为目录
file.getName()          ; // a.tcl, 返回文件名称, 如果filename带路径, getName()不包含路径
file.length()           ; // 3965 , 返回文件长度
file.lastModified()     ; // 1674873213000, 返回文件最后修改时间戳
file.getAbsolutePath()  ; // /a/b/c/../rpt/a.tcl, 返回文件绝对路径, 但没有解析掉"../"
file.getParent()        ; // ../rpt, 返回filename所在的目录名, String类型
file.getParentFile()    ; // 返回filename所在的目录, File类型
file.delete()           ; // 删除文件或目录, 如果目录不为空, 则删除不成功, 需要先删除目录中所有文件才可以

7.3 列出当前path下的文件

涉及两个函数: File.listFiles()和File.list().
区别是: File.listFiles()返回的是File对象, File.list()返回的是文件名.

以File.listFiles()为例说明:
如果File对象是一个路径, 则函数返回一个File数组;
如果File对象是一个文件, 则函数返回null值;

public File[] listFiles();
public File[] listFiles(FilenameFilter f);
public File[] listFiles(FileFilter f);

例1: listFiles()

import java.io.File          ;

public class Test{

    public static void main(String[] args){

        File f = new File("/path/a/");
        File[] files = f.listFiles(); //不给参数, 返回所有文件

        for (int i=0; i<files.length; i++){
            System.out.format("%d : %s", i, files[i].getName());
        }
    }
}

例2: listFiles(FilenameFilter f)

import java.io.File          ;
import java.io.FilenameFilter;

public class Test{

    public static void main(String[] args){

        //创建一个filenamefilter
        FilenameFilter filter = new FilenameFilter(){
            public boolean accept(File f, String name){
                return name.startsWith("12"); //只返回以12开头的文件.
            }
        }; //注意这里要有分号
        
        File f = new File("/path/a/");
        File[] files = f.listFiles(filter); //给参数FilenameFilter
        
        for (int i=0; i<files.length; i++){
            System.out.format("%d : %s", i, files[i].getName());
        }
    }
}

例3: listFiles(FileFilter f)

import java.io.File         ;
import java.io.FileFilter   ;

public class Test{

    public static void main(String[] args){

        //创建一个filefilter
        FileFilter filter = new FileFilter(){
            public boolean accept(File f){
                return f.getName().endsWith("txt"); //只返回以txt结尾的文件.
            }
        };
        
        File f = new File("/path/a/");
        File[] files = f.listFiles(filter); //给参数FileFilter
        
        for (int i=0; i<files.length; i++){
            System.out.format("%d : %s", i, files[i].getName());
        }
    }
}

7.4 列出path及子path下的所有文件

File.walk() 当前版本不支持, 还没试

7.5 进制转换

String s = "20";
int    i = Integer.valueOf(s).intValue(); // 20     字符串转整数 
String b = Integer.toBinaryString(i);     // 10100  整数转二进制
String h = Integer.toHexString(i);        // 14     整数转十六进制

int    w = 8;
String bw= String.format("%"+w+"s", b).replace(" ", "0"); 
// 00010100, 
// 1) 通过变量指定宽度(通过拼接format实现)
// 2) 不足位数填充0(通过替换实现)

7.6 取整

int i = 9;
int j = (int)Math.ceil((double)i/4); //向上取整

7.7 乘方

int i = (int)Math.pow(2, 3); //8, 2^3, 默认返回double类型, 如果需要整数, 需要转换

https://geek-docs.com/java/java-tutorial/dom.html

7.8 读取xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!-- note -->
<tiles>
    <tile name="t0" tile_dir="/a/b/c">
        <ports>
            <port name="p0"></port>
            <port name="p1"></port>
            <port name="p2"></port>
        </ports>
    </tile>
    <tile name="t1" tile_dir="/a/b/c">
        <ports>
        </ports>
    </tile>
    <tile name="t2" tile_dir="/a/b/c">
        <ports>
        </ports>
    </tile>
</tiles>

处理xml文件

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class A{
    public static main(String[] args){
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try{
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("../data/xx.xml");

            //取Element tiles,
            //注意, getElementsByTagName()返回的是list, 需要通过item(0)取出该节点.
            Element ele_tiles = (Element)doc.getElementsByTagName("tiles").item(0);

            //取出各个tile
            NodeList node_list_tiles = ele_tiles.getElementsByTagName("tile");

            //循环处理每个tile
            for(int idx_tile=0; idx_tile<node_list_tiles.getLength(); idx_tile++){
                //取第idx_tile个tile:
                Element ele_one_tile = (Element)node_list_tiles.item(idx_tile);
                
                //取属性
                String tile_name = ele_one_tile.getAttribute("name");
                String tile_dir = ele_one_tile.getAttribute("dir");

                //取ports
                List<String> list_ports = new ArrayList<>();
                Element ele_ports = (Element)ele_one_tile.getElementsByTagName("ports").item(0);
                NodeList node_list_port = ele_ports.getElementsByTagName("port");

                for(int idx_port=0; idx_port<node_list_port.getLength(); idx_port++){
                    Element ele_one_port = (Element)node_list_port.item(idx_port);
                    String port_name = ele_one_port.getAttribute("name");
                }
            }

        } catch (Exception e){
            e.printStackTrace();
        }
    }

}

posted @ 2023-01-28 16:20  编程驴子  阅读(20)  评论(0编辑  收藏  举报