Java 基础学习笔记
生活随笔
收集整理的這篇文章主要介紹了
Java 基础学习笔记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一.語法
1. 三元運(yùn)算?
y = (x>1)?'a':200;
2. switch
int a=4,b =2;
char ch = '+';
switch(ch)
{
case '-':
System.out.println(a-b);
break;
case '+':
System.out.println(a+b);
break;
case '*':
System.out.println(a*b);
break;
case '/':
System.out.println(a/b);
break;
default:
System.out.println("feifa");
}
3. 循環(huán)
while(先判斷) ?
do...while(先執(zhí)行行一次,在判斷)?
for(int x = 0; x<3 ; x++)
for(int x : args)
4. ?循環(huán)內(nèi)控制
continue; ?只能作用于循環(huán)結(jié)構(gòu)。繼續(xù)循環(huán)。特點(diǎn):結(jié)束本次循環(huán),繼續(xù)下一次循環(huán)。
break; ? ? 退出整個循環(huán)?
5. break 和 continue
w:for(int x=0; x<3; x++)
{
for(int y=0; y<4; y++)
{
System.out.println("x="+x);
break w;
continue w;
}
6. 函數(shù)
public class Fun {
public static void main(String[] args)?
{
int x = getMax(3,4);
}
public static int getMax(int a,int b)
{
return (a>b)?a:b;
}
}
7. 函數(shù)重載
public static int getMax(int a,int b){}
public static int getMax(char b){}
8. 數(shù)組(看 ?進(jìn)制轉(zhuǎn)換_經(jīng)典)
int[] x = new int[3];
int[] arr = new int[]{3,1,6,5,4};
int[][] arr = {{3,5,1,7},{2,3,5,8},{6,1,8,2}};
int[] x,y[];//x一維,y二維。
9. for 最小值加一,最大值減一
for(int start=0,end=arr.length-1; start
二。對象
1. 對象
1. private :私有。封裝。
2. 匿名對象
new Car().run();
3. 構(gòu)造代碼塊
給對象進(jìn)行初始化
{
cry(); ? //構(gòu)造代碼塊
}
4. 構(gòu)造函數(shù)
Person()
{
System.out.println("A: name="+name+",,age="+age);
}
5. this
this代表所屬對象
如果this要用在構(gòu)造函數(shù)內(nèi),只能用在第一行(或最前幾行), 構(gòu)造函數(shù)中調(diào)用其它的構(gòu)造函數(shù)要用 this() ?,只能在構(gòu)造函數(shù)間用這種方法
6. static
靜態(tài),,用于修飾成員(成員變量,成員函數(shù))
當(dāng)成員被靜態(tài)修飾后,就多了一個調(diào)用方式,除了可以被對象調(diào)用外,
還可以直接被類名調(diào)用。類名.靜態(tài)成員。
7. 靜態(tài)代碼塊。
static
{
靜態(tài)代碼塊中的執(zhí)行語句。
}
8. 加載順序
靜態(tài)代碼塊--構(gòu)造代碼塊--構(gòu)造函數(shù)--
9. 單例設(shè)計(jì)模式--餓漢式,懶漢式
? ?
餓漢式
class Single
{
private static final Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;
}
}
懶漢式
public class Lan {
private static Lan s = null;
private Single(){}
public static Lan getInstance()
{
if(s==null)
{
synchronized(Lan.class)
{
if(s==null)
s = new Single();
}
}
return s;
}
}
2. 繼承
class Student extends Person
{
void study()
{
System.out.println("good study");
}
}
1. super
2. 重寫(覆蓋)
子類覆蓋父類,必須保證子類權(quán)限大于等于父類權(quán)限,才可以覆蓋,否則編譯失敗。
靜態(tài)只能覆蓋靜態(tài)。
3. 子類中所有的構(gòu)造函數(shù)默認(rèn)第一行都是super()
3. 抽像 ?類 方法
abstract class Student
{
abstract final void study();
//abstract void study1();
void sleep()
{
System.out.println("躺著");
}
}
4. 接口
interface ??
接口中的成員都有固定修飾符。
常量:public static final
方法:public abstract?
implements ? 實(shí)現(xiàn)
5. 多態(tài)性
Animal a = new Cat();//類型提升,向上轉(zhuǎn)型
Cat c = (Cat)a; ?//千萬不要出現(xiàn)父類轉(zhuǎn)子類 這樣的操作(保留意見)
Fu a = new Zi(); ? 調(diào)用父類有,而子類沒有的方法,用父類的方法。
調(diào)用子類有,而父類沒有的方法,報(bào)錯
調(diào)用父類有,而子類也有的方法,用子類的方法復(fù)寫父類的方法。即調(diào)用的是子類的方法。
如果父類和子類用的都是static 靜態(tài)方法。用父類的方法
在多態(tài)中,成員變量的特點(diǎn):
無論編譯和運(yùn)行,都參考左邊(引用型變量所屬的類)。
在多態(tài)中,靜態(tài)成員函數(shù)的特點(diǎn):
無論編譯和運(yùn)行,都參考做左邊。
6. 內(nèi)部類
當(dāng)內(nèi)部類中定義了靜態(tài)成員,該內(nèi)部類必須是static的。
當(dāng)外部類中的靜態(tài)方法訪問內(nèi)部類時,內(nèi)部類也必須是static的。
內(nèi)部類定義在局部時,
不可以被成員修飾符修飾
可以直接訪問外部類中的成員,因?yàn)檫€持有外部類中的引用。
但是不可以訪問它所在的局部中的變量。只能訪問被final修飾的局部變量。
1. 靜態(tài)內(nèi)部類 ? --當(dāng)外部類中的靜態(tài)方法訪問內(nèi)部類時,內(nèi)部類也必須是static的。
2. 匿名內(nèi)部類 ? ?
定義匿名內(nèi)部類的前提:
內(nèi)部類必須是繼承一個類或者實(shí)現(xiàn)接口。
匿名內(nèi)部類的格式: ?new 父類或者接口(){定義子類的內(nèi)容}
匿名內(nèi)部類中定義的方法最好不要超過3個。
3.
三。異常 ? ? 實(shí)現(xiàn)接口的類中有異常不能throws ,只能try .因?yàn)?接口throws不出去
1.語法
try
{
需要被檢測的代碼;
}
catch(異常類 變量)
{
處理異常的代碼;(處理方式)
}
finally
{
一定會執(zhí)行的語句;
}
2. 獲取異常信息
String getMessage():
3.異常在子父類覆蓋中的體現(xiàn)
子類在覆蓋父類時,如果父類的方法拋出異常,那么子類的覆蓋方法,只能拋出父類的異常或者該異常的子類
8. 包之間的操作
2. import com.etaoko.packa.*;
1. protected ?
四。多線程
1. 多線程的兩種方法
1. extends Thread ? 覆蓋run() 方法,然后 .start() ? ... .start() 一個線程只能用一次
2. implements Runnable ??
覆蓋run() 方法,?
創(chuàng)建 實(shí)現(xiàn)Runnable 的對象
以Thread中(Runable target) 構(gòu)造函數(shù),創(chuàng)建線程
以Thread中(Runable target) 構(gòu)造函數(shù),創(chuàng)建線程
....
然后 .start()
.start()
....
2. 同步
1. Object obj = new Object(); ? 給同步創(chuàng)建鎖
synchronized (obj) {}; ? ? ? 同步,或用this鎖 synchronized (this) {}; 如果是static 用synchronized (類.class) {};?
2. public synchronized void add(int n) ? 在函數(shù)上同步,鎖是this,如果是static函數(shù),用 類名.class 對象鎖
3. 死鎖
五。線程間的通信
1. ?同步,如果兩個線程執(zhí)行的代碼不同,則同步時,要把兩個線程中的相關(guān)的代碼都同步,加同一個鎖
2. 等待喚醒機(jī)制 ?r.wait() ?r.notify(); r.notifyAll(); ? (全用在同步里)
r.notifyAll(); 用于有 多個生產(chǎn)者和多個消費(fèi)者 的時候,用 while 替換 if 判斷標(biāo)記,然后全部喚醒
while(!flag)
r.wait();
r.notifyAll();
3. Lock() ?jdk1.5 的版本
private Lock lock = ReentrantLock();
private Condition1 con = lock.newCondition();
private Condition2 con = lock.newCondition();
lock.lock();
try {
condition1.await();
condition2.signal();
}
finally{lock.unlock();}
4. 停止線程
1. 把循環(huán)停下來,以標(biāo)志位做為循環(huán)條件
2. 在同步中, ?Thread 中有個方法 interrupt() 中斷線程
t1.interrupt(); ?寫在主線程中,t1.start() 之后, 在線程中要用 ?try {} catch{ flag = false;}
5. 守護(hù)線程
t1.setDaemon(true); ? //主線程不在(或者說前臺線程都不在了),后臺線程自動停止
t2.setDaemon(true);
t1.start();
t2.start();
6. join()
t1.join(); t1要強(qiáng)奪CPU的執(zhí)行權(quán),這時,主線程是凍結(jié)狀態(tài),t1線程結(jié)束后,主線程才活過來,俗稱等t1去死
7. 優(yōu)先級
t1.start();
t1.setPriority(Thread.Max_PRIORITY);
max_priority
min_priority
norm_priority
8. yield()
暫停當(dāng)前正在執(zhí)行的線程對象,執(zhí)行其它線程
Thread.yield(); ?可以實(shí)現(xiàn)兩個線程交替執(zhí)行
六. String
String[] s3 =new String[]{"a","b","c"};
System.out.println(s1 == s2);
int num = s.codePointAt(0);
int num1 = s.indexOf('d');
System.out.println(s3.getClass());
System.out.println(s3);
System.out.println(new String(s3,2,2));
String a = String(s3);
System.out.println(a);
char[] abc = s.toCharArray();
byte[] abc = s.getBytes();
System.out.println(abc[3]);
String ss = "liusai,lius,liunan,zhangjian,zhangbi";
System.out.println(s.replace('a','x'));
System.out.println(s.replace("abc","xyz"));
String[] ss1 = ss.split(",");
System.out.println(s.substring(2));
System.out.println(s.substring(2,4));
System.out.println(s.toUpperCase().toLowerCase());
System.out.println(s.trim());
System.out.println(s.compareTo(s1));
StringBuffer ? //線程同步
StringBuffer sb = new StringBuffer();
sb = sb.append(34);
sb = sb.append("a");
sb = sb.append('a');
sb = sb.insert(2, "zzyyxxaabbcc");
sb = sb.delete(3, 5);
sb = sb.deleteCharAt(3);
sb = sb.delete(0, sb.length()); ?//清空StringBuffer
sb = sb.reverse();
System.out.println(sb);
char[] chs = new char[6];
sb.getChars(2, 5, chs,2); ? ?//將指定位置指定長度的字符存入 char 型數(shù)組
StringBuilder //與StringBuffer相同,但是線程不同步
對象的包裝類
byte Byte
short short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
基本數(shù)據(jù)類型改成字符串
基本數(shù)據(jù)類型+""; ? 或
基本數(shù)據(jù)類型.toString(基本數(shù)據(jù)類型值);
如: ?Integet.toString(34); ?//將34整數(shù)變成"34"
int num = Integet.parseInt("123"); ? //把字符串"123"變成整成123;
自動裝箱 ?1.5新特性
//Integer x = new Integer(4);
Integer x = 4; //自動裝箱
x = x +2; ? //1.5新特性,將 x 拆箱成int ,+2后在裝箱,但x不能為null;
Integer a = 127;
Integer b = 127; ? //a=b,因?yàn)?1.5新特性,如果在一個byte內(nèi),就不開劈新空間;
七。集合框架
1. ArrayList 最常用的集合 線程不同步 // (Vector ?線程同步) ? // LinkedList?
ArrayList a1 = new ArrayList();
a1.add("java01");
a1.add("java02");
a1.add("java03");
a1.add("java04");
System.out.println(a1);
ArrayList a2 = new ArrayList();
a2.add("java03");
a2.add("java04");
a2.add("java05");
a2.add("java06");
System.out.println(a2);
a1.retainAll(a2);
a1.addAll(a2);
a1.removeAll(a2);
System.out.println(a1);
a1.contains(obj) ?//判斷集合中的元素是否相同
2. 迭代器 ? Iterator //只能 .remove?
Iterator it = a1.iterator(); ? //但這種方法,變量it在while循環(huán)完后還存在,占用內(nèi)存。所以一般用for 循環(huán),將it變量定義在循環(huán)內(nèi)部
while(it.hasNext())
{
System.out.println(it.next());
}
for(Iterator it1 = a1.iterator();it1.hasNext();)
{
System.out.println(it1.next());
}
3. 迭代器 ListIterator // Iterator的子類,list集合特有,可以對集合 增,刪,改,查
ListIterator it = a1.listIterator();
while(it.hasNext())
{
System.out.println(it.next());
}
while(it.hasPrevious())
{
System.out.println(it.previous());
}
4. Vector //枚舉取出,與迭代器相同?
Enumeration en = v.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
5. LinkedList
LinkedList ll = new LinkedList();
ll.add("java01");
ll.add("java02");
ll.addFirst("java03");
ll.addLast("java04");
System.out.println(ll);
ll.removeFirst();
System.out.println(ll);
ll.pollFirst(); ?//remove
ll.peekFirst(); //get
ll.offerFirst(); //set
6. 存自定義類Person
取的時候要
Person p = (Person)ll.next();
7. List集合 用equals ,set集合用 hashCode?
8. HashSet ?// Set集合中的值無序,不允許有重復(fù)
HashSet 每存入一個值的時候,會和現(xiàn)有元素比較,(先用hashCope(),在用 equals())
所以,一般要復(fù)寫hashCope(),equals()
例: hashCope(){return name.hashCope()+age*39}?
9. TreeSet //不以存入先后為序,但以元素的比值排序了
因?yàn)橐判?#xff0c;所以,TreeSet中的元素要據(jù)有比較性,或者叫容器自身據(jù)有比較性。以容器比較性優(yōu)先
所以要 implements Comparable ,并復(fù)寫
TreeSet ts = new TreeSet();
ts.add(new Student("jiangxi",29));
ts.add(new Student("runyu",25));
ts.add(new Student("liusai",25));
ts.add(new Student("lixiao",31));
Iterator it = ts.iterator();
while(it.hasNext()){
Student stu = (Student)it.next();
System.out.println(stu.getName());
}
public int compareTo(Object obj)?
{
if(!(obj instanceof Student))
throw new RuntimeException("not is Student");
Student s = (Student) obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name);
return -1;
}
TreeSet ts = new TreeSet(new MyCompare); //較常用
10. 泛型
eques(); 方法不能用泛型
TreeSet ts = new TreeSet(); ?使用泛型
?//定義泛型類,泛型類,QQ就是一個泛型,可以指定任意類型
public class FanXing {
private QQ q;
public QQ getQ() {
return q;
}
public void setQ(QQ q) {
this.q = q;
}
}
類上定義的泛型對整個對象有校
泛型定義在方法上
public void show(T t)
靜態(tài)方法上的泛型
靜態(tài)方法不可以訪問類上定義的泛型,
如果靜態(tài)方法操作的應(yīng)用數(shù)據(jù)類型不確定,可以將泛型定義在方法上
public static void method(W t){} //泛型放在返回值類型的前面
泛型定義在接口上
interface Inter
class Aa implements Inter ? ?// 泛型在定義類的時候指定,創(chuàng)建Aa對象的時候就不能指定了
class Aa implements Inter ? ?//創(chuàng)建Aa類的時候不指定T的類型,則可以在創(chuàng)建Aa對象的時候指定
泛型通配符 ?
用 ? 不能使用類型特有方法
泛型限定
? extends Person ?上限
? super E ? ? 下限
11. Map 集合
key -- value; ?Map存的是鍵與值的映射關(guān)系
Hashtable ?不可以存null ,同步
HashMap ? ?哈希表數(shù)據(jù)結(jié)構(gòu),允許Null,不同步
TreeMap 二駐樹,不同步,可以用于給map集合中的鍵排序
和set 很像
其實(shí)set底層就是使用了map集合
HashMap hm = new HashMap();
hm.put("a1", 1);
hm.put("a2",2);
hm.put("a3", "aaaa");
hm.put(1, 4);
System.out.println(hm.get(null));
System.out.println(hm);
map.put的時候,如果有重復(fù)鍵,將把此鍵的原來的值返回,并用新值替換原來的值
keySet : 把map每個鍵的值,都存入Set集合
Set keySet = map.keySet(); ?//然后可用迭代器取出 keySet 的值?
entrySet() : 把映射關(guān)系存入Set集合,類型為 Map.Entry
Set> entrySet = hm.entrySet();
Iterator> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry me = it.next();
String key = me.getKey();
String value = me.getValue();
System.out.println(key+"...."+value);
}
12. 工具類
Collections 對集合進(jìn)行操作
Collections.sort(list); 對list進(jìn)行排序;
Collection.max();
Collection.binarySearch(); ?//二分搜索,以獲得指定對象,必須有序
Collection.reverse(); ? ? ?
TreeSet ts = new TreeSet(Collections.reverseOrder()); ?//反轉(zhuǎn)集合順序
TreeSet ts = new TreeSet(Collections.reverseOrder(比較類)); ?//把現(xiàn)有的比較類反轉(zhuǎn)
Collection.synchronizedList() ?//將list同步
Collection.synchronizedMap() ? //將Map集合同步
Collection.shuffle(list); ?//重新隨機(jī)排放元素
13. Arrays
對數(shù)組進(jìn)行操作
八。其它對象
1. System ? //Properties ?集合,hashTable的子類,屬于Map
System.out.println(System.getProperty("mykey"));
Properties prop = System.getProperties();
System.setProperty("mykey", "myvalue");
//java -Dmykey=myvalue 1.java
for(Object obj : prop.keySet())
{
String value = (String)prop.get(obj);
System.out.println(obj+"...::..."+value);
}
2. Runtime?
Runtime r = Runtime.getRuntime(); ??
Process p = r.exec("mstsc.exe"); ? //打開系統(tǒng)程序
Process p1 = r.exec(notepad.exe Index.java); ?//用notepad 打開Index.java文本文件
p.destroy(); ?//殺死進(jìn)程
3. Date || Calendar
Date d = new Date();
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E hh:mm:ss");
String time = sdf.format(d);
System.out.println(time);
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR));
c.set(2012,2,23); ? // 2 表示3月
c.add(Calendar.DAY_OF_MONTH,-8);
4. Math
double d = Math.ceil(16.34); ?17
double d1 = Math.floor(12.34); ?12
long l =Math.round(); ?四舍五入
double d2 = Math.pow(2,3) ?2的3次方
int dd = (int)(Math.random()*10+1); ? ?//產(chǎn)生隨機(jī)數(shù)
Random r = new java.util.Random; int dd = r.nextInt(10); //也是產(chǎn)生隨機(jī)數(shù)
九。IO流
InputStream ?OutputStream Reader Writer
1. FileWriter
FileWriter fw = new FileWriter("demo.txt"); ?//創(chuàng)建空文件,如果已存在,則覆蓋
FileWriter fw = new FileWriter("demo.txt",true); ?//如果已存在,則在文件中追加,如果不存在,創(chuàng)建此文件
fw.write("abcde\r\nsdfsd"); ?//在緩沖,沒寫到文件,\r\n是換行
fw.flush(); ? ? ? ?//刷新到文件
fw.close(); ? ? ?//刷新并關(guān)閉
2. IO異常處理
FileWriter fw = null;
try?
{
fw = new FileWriter("demo.txt",true);
fw.write("abcde"); ?//在緩沖,沒寫到文件
fw.flush(); ? ? ? ?//刷新到文件
}?
catch (IOException e)?
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try?
{
if(fw!=null)
fw.close();
}?
catch (IOException e)?
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3. FileReader
FileReader fr = new FileReader("demo.txt");
fr.read(); ?讀一個節(jié)符,返回 -1 則表示讀完
char[] buf = new char[3];
fr.read(buf); ? //數(shù)據(jù)長3,所以讀3個字符后就不讀了
char[] buf1 = new char[3];
fr.read(buf1); ? //繼續(xù)讀下面的字符
4. 讀入字符數(shù)組
char[] buf = new char[1024];
int num = 0;
while((num=frr.read(buf)) != -1)
{
System.out.println(new String(buf,0,num));
}
frr.close();
5. BufferedWriter ?字符寫緩沖區(qū)
FileWrite fw = new FileWriter("buf.txt");
BufferedWriter bufw = new BufferedWriter(fw);
bufw.write("abcde");
bufw.newLine(); //寫入一個行分隔符
bufw.flush();
bufw.close();
6. BufferedReader ?//字符讀緩沖區(qū)
bufr.readLine(); ? ?//一次讀一行,但不包括換行符
FileReader fr = new FileReader("demo.txt");
BufferedReader bufr = new BufferedReader(fr);
String line = null;
while((line=bufr.readLine()) != null )
{
System.out.println(line); ?
}
bufr.close();
7. 裝飾設(shè)計(jì)模式
對原有對象的功能的增強(qiáng),要傳入一個對象
8. 裝飾與繼承的區(qū)別
MyReader
|--MyT
|--MyBufferT
|--MyM
|--MyBufferM
這樣,MyReader 類下每多一個子類,就要在子類上加一個MyBuffer
而裝飾類可以接收一個MyReader類型的對象,然后對這個對象進(jìn)行增強(qiáng)
9. LineNumberReader 類
setLineNumberReader(100); ? //設(shè)置第一行的行號為100,第二行為101....
getLineNumberReader(); ? ? ? 顯示行號
11. OutputStream ?寫,InputStream ?讀
FileOutputStream fos = new FileOutputStream("fos.txt");
fos.write("abcde".getBytes()); ?//不用flush,直接進(jìn)文件
fos.close();
FileInputStream fis = new FileInputStream("fos.txt"); ? //讀文件
byte[] a = new byte[5];
int ch = 0;
while((ch = fis.read(a)) != -1)
{
System.out.println(new String(a,0,ch));
picw.write(a,0,ch);
}
fis.available();
12. BufferedStream ?//字節(jié)讀寫緩沖區(qū)
BufferedInputStream bufis = new BufferedInputStream(new BufferedInputStream("c:/2.mp3"));
BufferedOutputStream bufis = new BufferedOutputStream(new BufferedOutputStream("c:/1.mp3"));
13. 讀取鍵盤錄入
BufferedReader bufw = new BufferedReader(new OutputStreamReader(System.in));
寫入鍵盤輸出
BufferedWriter bufw = new BufferedWriter(new OutputStreamWrite(System.out));
改變鍵盤錄入源
System.setIn(new FileInputStream("aa.java"));
System.setOut(new PrintStream("aa.java"));
PrintStream("aaa.txt"); ?把輸出信息輸入到文件
14. File?
File f = new File("file.txt");
f.createNewfile(); ? //沒有,則創(chuàng)建文件,有,則不創(chuàng)建
deleteOnExit();
f.delete();
f.canExecute(); ?//是否可執(zhí)行
f.exists() ? ?是否存在
f.mkdir ?//創(chuàng)建file.txt名的文件夾
f.mkdirs ?//創(chuàng)建多級文件夾
f.isFile(); ? 是不是文件
f.isDirectory(); ? ?是不是目錄
f.isHidden(); ? //是不是隱藏文件
f.isAbsolute(); ? ? 參數(shù)中的文件是不是絕對路徑,不管這個文件是否存在
f.getName();
f.getPath(); ? ?相對路徑包含文件名
f.getParent(); ? //參數(shù)中指定了絕對路徑,則返回絕對路徑(不包含文件名),否則為null
f.getAbsolutePath(); ? ? 絕對路徑包含文件名
f.lastModified(); ? 最后修改時間
f.length(); ? 大小
File f1 = new File("file1.txt");
f.renameTo(f1) ? 重命名,或移動文件
File[] files = File.listRoots();
for(File f : files){System.out.println(f);} ? //得到系統(tǒng)現(xiàn)有的盤符
File f = new File("c"\\");
String[] names = f.list();
for(String name : names ) { System.out.println(name); } ?//打印C盤下所有文件?
FilenameFilter ?是個接口類型 ,接口下只有一個方法
取download 目錄下的.txt
File dir = new File("D:/Download");
String[] arr = dir.list(new FilenameFilter()
{
public boolean accept(File dir,String name)
{
return name.endsWith(".txt");
}
}
);
for(String name : arr) {System.out.println(name);}
f.listFiles() ?//獲取文件夾下的文件對象
Properties ?hashtable 的子類。
Properties prop = new Properties();
File file = new File("count.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
int count=0;
String value = prop.getProperty("time");
if(value!=null)
count=Integer.parseInt(value);
count++;
prop.setProperty("time",count+"");
FileOutputstream fos = new FileOutputStream(file);
prop.store(fos,"");
fos.close();
fis.close();
PrintStream();
PrintWriter();
SequenceInputStream; ?合并流
切割文件
FileInputStream fis = new FileInputStream("c:\\1.bmp");
FileOutputStream fos = null;
byte[] buf = new byte[1024*1024];
int len=0;
int count =1;
while((len=fis.read(buf)) != -1 )
{
fos=new FileOutputStream("c:\splitfiles\\"+(count++)+".part");
fos.write(buf,0,len);
fos.close();
}
fis.close();
對象的持久化,把對象存在硬盤上
類 implements Serializable 才能被序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.class"));
oos.writeobject(new Person()); ?寫硬盤
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person1.class"));
oos.writeobject(new Person()); ?寫硬盤
ObjectInputStream
Person.Object
從硬盤上讀一個對象
ObjectInputStream oos = new ObjectInputStream("Person.class"); ??
Person p = (Person)ois.readObject(); ?讀硬盤?
Person p1 = (Person)ois.readObject(); ?讀硬盤?
public static final long serialVersionUID = 42L; ?自己定義UID,為了序列化方便
靜態(tài)是不能被序列化的
transient int age; transient 關(guān)鍵字修飾的 ?也不能被序列化
管道流
管道輸入流 ? 管道輸出流
PipedInputStream in = new PipedInputStream ();
PipedOutputStream out = new PipedOutputStream();
Read r = new Read(in); ? //線程類
Write w = new Write(out); ?//線程類
RandomAccessFile ?隨機(jī)訪問文件,只能操作文件。可讀,也可寫
r ?讀文件,文件不存在報(bào)異常
rw ?讀寫,文件若存在,不會覆蓋
RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
raf.write("李四".getBytes());
raf.write(97); ? 這里的97會變成 a ,碼表
RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
raf.read(buf); ?//讀
raf.seek(8); ? //調(diào)整對象中指針
可隨機(jī)讀,也可以隨機(jī)寫,如果所寫的指針上有數(shù)據(jù),則被覆蓋
DataStream ?操作基本數(shù)據(jù)類型的流對象
ByteArrayInputStream?
OutputStreamWriter ?轉(zhuǎn)換流,字節(jié)轉(zhuǎn)字符輸出到硬盤文件
InputStreamReader ? ? ? ? ? 字符文件輸入到內(nèi)存轉(zhuǎn)字節(jié)
十。網(wǎng)絡(luò)
1. 獲取IP地址
i1 = InetAddress.getByName("www.baidu.com");
System.out.println(i1.toString());
System.out.println(i1.getHostAddress());
System.out.println(i1.getHostName());
2. 獲取IP地址數(shù)組
InetAddress i1[] = InetAddress.getAllByName("www.baidu.com");
3. UDP 無連接,一次不能超過64K
發(fā)送數(shù)據(jù)包
DatagramSocket ds = null;
ds = new DatagramSocket(10000); ? //端口,不指定則隨機(jī)
byte[] buf = "udp ge men lai le".getBytes();
DatagramPacket dp = null;
dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("172.16.2.109"),1000);
ds.send(dp);
ds.close();
接收數(shù)據(jù)包
DatagramSocket ds = null;
ds = new DatagramSocket(10000);
while(true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = null;
dp = new DatagramPacket(buf,buf.length);
ds.recive(dp);
String ip = ip.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
}
ds.close();
TCP ?面向連接--客戶端
Socket s = new Socket("192.168.1.254",10003);
OutputStream out = s.getOutputStream();
out.write("tcp ge men lai le ".getBytes());
byte[] buf = new byte[1024];
int len.read(buf);
System.out.println(new String(buf,0,len));
s.close();
TCP 服務(wù)端 ? //socket可關(guān)閉,可不關(guān)閉
ServerSocket ss = new ServerSocket(10003);
Socket s = ss.accept(); ? //接收客戶端數(shù)據(jù)
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
OutputStream out = s.getOutputStream();
out.write("Hello World!".getBytes());
s.close(); ?//關(guān)閉客戶端;
ss.close(); ?可選
4. URL ?
URL url = new URL("http://192.168.1.254/myweb/demo.html?name=haha&age=30");
int port = getPort();
if(port==-1)
port = 80;
System.out.println("getProtocol() :"+url.getProtocol());
System.out.println("getHost() :"+url.getHost());
System.out.println("getPort() :"+url.getPort()); ? ? ? ? ? ? ? //
System.out.println("getPath() :"+url.getPath());
System.out.println("getFile() :"+url.getFile());
System.out.println("getQuery() :"+url.getQuery());
5. URLConnection
URL url = new URL("http://192.168.1.254:8080/myweb/demo.html");
URLConnection conn = url.openConnection();
System.out.println(conn);
InputStream in = conn.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
1. 三元運(yùn)算?
y = (x>1)?'a':200;
2. switch
int a=4,b =2;
char ch = '+';
switch(ch)
{
case '-':
System.out.println(a-b);
break;
case '+':
System.out.println(a+b);
break;
case '*':
System.out.println(a*b);
break;
case '/':
System.out.println(a/b);
break;
default:
System.out.println("feifa");
}
3. 循環(huán)
while(先判斷) ?
do...while(先執(zhí)行行一次,在判斷)?
for(int x = 0; x<3 ; x++)
for(int x : args)
4. ?循環(huán)內(nèi)控制
continue; ?只能作用于循環(huán)結(jié)構(gòu)。繼續(xù)循環(huán)。特點(diǎn):結(jié)束本次循環(huán),繼續(xù)下一次循環(huán)。
break; ? ? 退出整個循環(huán)?
5. break 和 continue
w:for(int x=0; x<3; x++)
{
for(int y=0; y<4; y++)
{
System.out.println("x="+x);
break w;
continue w;
}
6. 函數(shù)
public class Fun {
public static void main(String[] args)?
{
int x = getMax(3,4);
}
public static int getMax(int a,int b)
{
return (a>b)?a:b;
}
}
7. 函數(shù)重載
public static int getMax(int a,int b){}
public static int getMax(char b){}
8. 數(shù)組(看 ?進(jìn)制轉(zhuǎn)換_經(jīng)典)
int[] x = new int[3];
int[] arr = new int[]{3,1,6,5,4};
int[][] arr = {{3,5,1,7},{2,3,5,8},{6,1,8,2}};
int[] x,y[];//x一維,y二維。
9. for 最小值加一,最大值減一
for(int start=0,end=arr.length-1; start
二。對象
1. 對象
1. private :私有。封裝。
2. 匿名對象
new Car().run();
3. 構(gòu)造代碼塊
給對象進(jìn)行初始化
{
cry(); ? //構(gòu)造代碼塊
}
4. 構(gòu)造函數(shù)
Person()
{
System.out.println("A: name="+name+",,age="+age);
}
5. this
this代表所屬對象
如果this要用在構(gòu)造函數(shù)內(nèi),只能用在第一行(或最前幾行), 構(gòu)造函數(shù)中調(diào)用其它的構(gòu)造函數(shù)要用 this() ?,只能在構(gòu)造函數(shù)間用這種方法
6. static
靜態(tài),,用于修飾成員(成員變量,成員函數(shù))
當(dāng)成員被靜態(tài)修飾后,就多了一個調(diào)用方式,除了可以被對象調(diào)用外,
還可以直接被類名調(diào)用。類名.靜態(tài)成員。
7. 靜態(tài)代碼塊。
static
{
靜態(tài)代碼塊中的執(zhí)行語句。
}
8. 加載順序
靜態(tài)代碼塊--構(gòu)造代碼塊--構(gòu)造函數(shù)--
9. 單例設(shè)計(jì)模式--餓漢式,懶漢式
? ?
餓漢式
class Single
{
private static final Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;
}
}
懶漢式
public class Lan {
private static Lan s = null;
private Single(){}
public static Lan getInstance()
{
if(s==null)
{
synchronized(Lan.class)
{
if(s==null)
s = new Single();
}
}
return s;
}
}
2. 繼承
class Student extends Person
{
void study()
{
System.out.println("good study");
}
}
1. super
2. 重寫(覆蓋)
子類覆蓋父類,必須保證子類權(quán)限大于等于父類權(quán)限,才可以覆蓋,否則編譯失敗。
靜態(tài)只能覆蓋靜態(tài)。
3. 子類中所有的構(gòu)造函數(shù)默認(rèn)第一行都是super()
3. 抽像 ?類 方法
abstract class Student
{
abstract final void study();
//abstract void study1();
void sleep()
{
System.out.println("躺著");
}
}
4. 接口
interface ??
接口中的成員都有固定修飾符。
常量:public static final
方法:public abstract?
implements ? 實(shí)現(xiàn)
5. 多態(tài)性
Animal a = new Cat();//類型提升,向上轉(zhuǎn)型
Cat c = (Cat)a; ?//千萬不要出現(xiàn)父類轉(zhuǎn)子類 這樣的操作(保留意見)
Fu a = new Zi(); ? 調(diào)用父類有,而子類沒有的方法,用父類的方法。
調(diào)用子類有,而父類沒有的方法,報(bào)錯
調(diào)用父類有,而子類也有的方法,用子類的方法復(fù)寫父類的方法。即調(diào)用的是子類的方法。
如果父類和子類用的都是static 靜態(tài)方法。用父類的方法
在多態(tài)中,成員變量的特點(diǎn):
無論編譯和運(yùn)行,都參考左邊(引用型變量所屬的類)。
在多態(tài)中,靜態(tài)成員函數(shù)的特點(diǎn):
無論編譯和運(yùn)行,都參考做左邊。
6. 內(nèi)部類
當(dāng)內(nèi)部類中定義了靜態(tài)成員,該內(nèi)部類必須是static的。
當(dāng)外部類中的靜態(tài)方法訪問內(nèi)部類時,內(nèi)部類也必須是static的。
內(nèi)部類定義在局部時,
不可以被成員修飾符修飾
可以直接訪問外部類中的成員,因?yàn)檫€持有外部類中的引用。
但是不可以訪問它所在的局部中的變量。只能訪問被final修飾的局部變量。
1. 靜態(tài)內(nèi)部類 ? --當(dāng)外部類中的靜態(tài)方法訪問內(nèi)部類時,內(nèi)部類也必須是static的。
2. 匿名內(nèi)部類 ? ?
定義匿名內(nèi)部類的前提:
內(nèi)部類必須是繼承一個類或者實(shí)現(xiàn)接口。
匿名內(nèi)部類的格式: ?new 父類或者接口(){定義子類的內(nèi)容}
匿名內(nèi)部類中定義的方法最好不要超過3個。
3.
三。異常 ? ? 實(shí)現(xiàn)接口的類中有異常不能throws ,只能try .因?yàn)?接口throws不出去
1.語法
try
{
需要被檢測的代碼;
}
catch(異常類 變量)
{
處理異常的代碼;(處理方式)
}
finally
{
一定會執(zhí)行的語句;
}
2. 獲取異常信息
String getMessage():
3.異常在子父類覆蓋中的體現(xiàn)
子類在覆蓋父類時,如果父類的方法拋出異常,那么子類的覆蓋方法,只能拋出父類的異常或者該異常的子類
8. 包之間的操作
2. import com.etaoko.packa.*;
1. protected ?
四。多線程
1. 多線程的兩種方法
1. extends Thread ? 覆蓋run() 方法,然后 .start() ? ... .start() 一個線程只能用一次
2. implements Runnable ??
覆蓋run() 方法,?
創(chuàng)建 實(shí)現(xiàn)Runnable 的對象
以Thread中(Runable target) 構(gòu)造函數(shù),創(chuàng)建線程
以Thread中(Runable target) 構(gòu)造函數(shù),創(chuàng)建線程
....
然后 .start()
.start()
....
2. 同步
1. Object obj = new Object(); ? 給同步創(chuàng)建鎖
synchronized (obj) {}; ? ? ? 同步,或用this鎖 synchronized (this) {}; 如果是static 用synchronized (類.class) {};?
2. public synchronized void add(int n) ? 在函數(shù)上同步,鎖是this,如果是static函數(shù),用 類名.class 對象鎖
3. 死鎖
五。線程間的通信
1. ?同步,如果兩個線程執(zhí)行的代碼不同,則同步時,要把兩個線程中的相關(guān)的代碼都同步,加同一個鎖
2. 等待喚醒機(jī)制 ?r.wait() ?r.notify(); r.notifyAll(); ? (全用在同步里)
r.notifyAll(); 用于有 多個生產(chǎn)者和多個消費(fèi)者 的時候,用 while 替換 if 判斷標(biāo)記,然后全部喚醒
while(!flag)
r.wait();
r.notifyAll();
3. Lock() ?jdk1.5 的版本
private Lock lock = ReentrantLock();
private Condition1 con = lock.newCondition();
private Condition2 con = lock.newCondition();
lock.lock();
try {
condition1.await();
condition2.signal();
}
finally{lock.unlock();}
4. 停止線程
1. 把循環(huán)停下來,以標(biāo)志位做為循環(huán)條件
2. 在同步中, ?Thread 中有個方法 interrupt() 中斷線程
t1.interrupt(); ?寫在主線程中,t1.start() 之后, 在線程中要用 ?try {} catch{ flag = false;}
5. 守護(hù)線程
t1.setDaemon(true); ? //主線程不在(或者說前臺線程都不在了),后臺線程自動停止
t2.setDaemon(true);
t1.start();
t2.start();
6. join()
t1.join(); t1要強(qiáng)奪CPU的執(zhí)行權(quán),這時,主線程是凍結(jié)狀態(tài),t1線程結(jié)束后,主線程才活過來,俗稱等t1去死
7. 優(yōu)先級
t1.start();
t1.setPriority(Thread.Max_PRIORITY);
max_priority
min_priority
norm_priority
8. yield()
暫停當(dāng)前正在執(zhí)行的線程對象,執(zhí)行其它線程
Thread.yield(); ?可以實(shí)現(xiàn)兩個線程交替執(zhí)行
六. String
String[] s3 =new String[]{"a","b","c"};
System.out.println(s1 == s2);
int num = s.codePointAt(0);
int num1 = s.indexOf('d');
System.out.println(s3.getClass());
System.out.println(s3);
System.out.println(new String(s3,2,2));
String a = String(s3);
System.out.println(a);
char[] abc = s.toCharArray();
byte[] abc = s.getBytes();
System.out.println(abc[3]);
String ss = "liusai,lius,liunan,zhangjian,zhangbi";
System.out.println(s.replace('a','x'));
System.out.println(s.replace("abc","xyz"));
String[] ss1 = ss.split(",");
System.out.println(s.substring(2));
System.out.println(s.substring(2,4));
System.out.println(s.toUpperCase().toLowerCase());
System.out.println(s.trim());
System.out.println(s.compareTo(s1));
StringBuffer ? //線程同步
StringBuffer sb = new StringBuffer();
sb = sb.append(34);
sb = sb.append("a");
sb = sb.append('a');
sb = sb.insert(2, "zzyyxxaabbcc");
sb = sb.delete(3, 5);
sb = sb.deleteCharAt(3);
sb = sb.delete(0, sb.length()); ?//清空StringBuffer
sb = sb.reverse();
System.out.println(sb);
char[] chs = new char[6];
sb.getChars(2, 5, chs,2); ? ?//將指定位置指定長度的字符存入 char 型數(shù)組
StringBuilder //與StringBuffer相同,但是線程不同步
對象的包裝類
byte Byte
short short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
基本數(shù)據(jù)類型改成字符串
基本數(shù)據(jù)類型+""; ? 或
基本數(shù)據(jù)類型.toString(基本數(shù)據(jù)類型值);
如: ?Integet.toString(34); ?//將34整數(shù)變成"34"
int num = Integet.parseInt("123"); ? //把字符串"123"變成整成123;
自動裝箱 ?1.5新特性
//Integer x = new Integer(4);
Integer x = 4; //自動裝箱
x = x +2; ? //1.5新特性,將 x 拆箱成int ,+2后在裝箱,但x不能為null;
Integer a = 127;
Integer b = 127; ? //a=b,因?yàn)?1.5新特性,如果在一個byte內(nèi),就不開劈新空間;
七。集合框架
1. ArrayList 最常用的集合 線程不同步 // (Vector ?線程同步) ? // LinkedList?
ArrayList a1 = new ArrayList();
a1.add("java01");
a1.add("java02");
a1.add("java03");
a1.add("java04");
System.out.println(a1);
ArrayList a2 = new ArrayList();
a2.add("java03");
a2.add("java04");
a2.add("java05");
a2.add("java06");
System.out.println(a2);
a1.retainAll(a2);
a1.addAll(a2);
a1.removeAll(a2);
System.out.println(a1);
a1.contains(obj) ?//判斷集合中的元素是否相同
2. 迭代器 ? Iterator //只能 .remove?
Iterator it = a1.iterator(); ? //但這種方法,變量it在while循環(huán)完后還存在,占用內(nèi)存。所以一般用for 循環(huán),將it變量定義在循環(huán)內(nèi)部
while(it.hasNext())
{
System.out.println(it.next());
}
for(Iterator it1 = a1.iterator();it1.hasNext();)
{
System.out.println(it1.next());
}
3. 迭代器 ListIterator // Iterator的子類,list集合特有,可以對集合 增,刪,改,查
ListIterator it = a1.listIterator();
while(it.hasNext())
{
System.out.println(it.next());
}
while(it.hasPrevious())
{
System.out.println(it.previous());
}
4. Vector //枚舉取出,與迭代器相同?
Enumeration en = v.elements();
while(en.hasMoreElements())
{
System.out.println(en.nextElement());
}
5. LinkedList
LinkedList ll = new LinkedList();
ll.add("java01");
ll.add("java02");
ll.addFirst("java03");
ll.addLast("java04");
System.out.println(ll);
ll.removeFirst();
System.out.println(ll);
ll.pollFirst(); ?//remove
ll.peekFirst(); //get
ll.offerFirst(); //set
6. 存自定義類Person
取的時候要
Person p = (Person)ll.next();
7. List集合 用equals ,set集合用 hashCode?
8. HashSet ?// Set集合中的值無序,不允許有重復(fù)
HashSet 每存入一個值的時候,會和現(xiàn)有元素比較,(先用hashCope(),在用 equals())
所以,一般要復(fù)寫hashCope(),equals()
例: hashCope(){return name.hashCope()+age*39}?
9. TreeSet //不以存入先后為序,但以元素的比值排序了
因?yàn)橐判?#xff0c;所以,TreeSet中的元素要據(jù)有比較性,或者叫容器自身據(jù)有比較性。以容器比較性優(yōu)先
所以要 implements Comparable ,并復(fù)寫
TreeSet ts = new TreeSet();
ts.add(new Student("jiangxi",29));
ts.add(new Student("runyu",25));
ts.add(new Student("liusai",25));
ts.add(new Student("lixiao",31));
Iterator it = ts.iterator();
while(it.hasNext()){
Student stu = (Student)it.next();
System.out.println(stu.getName());
}
public int compareTo(Object obj)?
{
if(!(obj instanceof Student))
throw new RuntimeException("not is Student");
Student s = (Student) obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name);
return -1;
}
TreeSet ts = new TreeSet(new MyCompare); //較常用
10. 泛型
eques(); 方法不能用泛型
TreeSet ts = new TreeSet(); ?使用泛型
?//定義泛型類,泛型類,QQ就是一個泛型,可以指定任意類型
public class FanXing {
private QQ q;
public QQ getQ() {
return q;
}
public void setQ(QQ q) {
this.q = q;
}
}
類上定義的泛型對整個對象有校
泛型定義在方法上
public void show(T t)
靜態(tài)方法上的泛型
靜態(tài)方法不可以訪問類上定義的泛型,
如果靜態(tài)方法操作的應(yīng)用數(shù)據(jù)類型不確定,可以將泛型定義在方法上
public static void method(W t){} //泛型放在返回值類型的前面
泛型定義在接口上
interface Inter
class Aa implements Inter ? ?// 泛型在定義類的時候指定,創(chuàng)建Aa對象的時候就不能指定了
class Aa implements Inter ? ?//創(chuàng)建Aa類的時候不指定T的類型,則可以在創(chuàng)建Aa對象的時候指定
泛型通配符 ?
用 ? 不能使用類型特有方法
泛型限定
? extends Person ?上限
? super E ? ? 下限
11. Map 集合
key -- value; ?Map存的是鍵與值的映射關(guān)系
Hashtable ?不可以存null ,同步
HashMap ? ?哈希表數(shù)據(jù)結(jié)構(gòu),允許Null,不同步
TreeMap 二駐樹,不同步,可以用于給map集合中的鍵排序
和set 很像
其實(shí)set底層就是使用了map集合
HashMap hm = new HashMap();
hm.put("a1", 1);
hm.put("a2",2);
hm.put("a3", "aaaa");
hm.put(1, 4);
System.out.println(hm.get(null));
System.out.println(hm);
map.put的時候,如果有重復(fù)鍵,將把此鍵的原來的值返回,并用新值替換原來的值
keySet : 把map每個鍵的值,都存入Set集合
Set keySet = map.keySet(); ?//然后可用迭代器取出 keySet 的值?
entrySet() : 把映射關(guān)系存入Set集合,類型為 Map.Entry
Set> entrySet = hm.entrySet();
Iterator> it = entrySet.iterator();
while(it.hasNext())
{
Map.Entry me = it.next();
String key = me.getKey();
String value = me.getValue();
System.out.println(key+"...."+value);
}
12. 工具類
Collections 對集合進(jìn)行操作
Collections.sort(list); 對list進(jìn)行排序;
Collection.max();
Collection.binarySearch(); ?//二分搜索,以獲得指定對象,必須有序
Collection.reverse(); ? ? ?
TreeSet ts = new TreeSet(Collections.reverseOrder()); ?//反轉(zhuǎn)集合順序
TreeSet ts = new TreeSet(Collections.reverseOrder(比較類)); ?//把現(xiàn)有的比較類反轉(zhuǎn)
Collection.synchronizedList() ?//將list同步
Collection.synchronizedMap() ? //將Map集合同步
Collection.shuffle(list); ?//重新隨機(jī)排放元素
13. Arrays
對數(shù)組進(jìn)行操作
八。其它對象
1. System ? //Properties ?集合,hashTable的子類,屬于Map
System.out.println(System.getProperty("mykey"));
Properties prop = System.getProperties();
System.setProperty("mykey", "myvalue");
//java -Dmykey=myvalue 1.java
for(Object obj : prop.keySet())
{
String value = (String)prop.get(obj);
System.out.println(obj+"...::..."+value);
}
2. Runtime?
Runtime r = Runtime.getRuntime(); ??
Process p = r.exec("mstsc.exe"); ? //打開系統(tǒng)程序
Process p1 = r.exec(notepad.exe Index.java); ?//用notepad 打開Index.java文本文件
p.destroy(); ?//殺死進(jìn)程
3. Date || Calendar
Date d = new Date();
System.out.println(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E hh:mm:ss");
String time = sdf.format(d);
System.out.println(time);
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.YEAR));
c.set(2012,2,23); ? // 2 表示3月
c.add(Calendar.DAY_OF_MONTH,-8);
4. Math
double d = Math.ceil(16.34); ?17
double d1 = Math.floor(12.34); ?12
long l =Math.round(); ?四舍五入
double d2 = Math.pow(2,3) ?2的3次方
int dd = (int)(Math.random()*10+1); ? ?//產(chǎn)生隨機(jī)數(shù)
Random r = new java.util.Random; int dd = r.nextInt(10); //也是產(chǎn)生隨機(jī)數(shù)
九。IO流
InputStream ?OutputStream Reader Writer
1. FileWriter
FileWriter fw = new FileWriter("demo.txt"); ?//創(chuàng)建空文件,如果已存在,則覆蓋
FileWriter fw = new FileWriter("demo.txt",true); ?//如果已存在,則在文件中追加,如果不存在,創(chuàng)建此文件
fw.write("abcde\r\nsdfsd"); ?//在緩沖,沒寫到文件,\r\n是換行
fw.flush(); ? ? ? ?//刷新到文件
fw.close(); ? ? ?//刷新并關(guān)閉
2. IO異常處理
FileWriter fw = null;
try?
{
fw = new FileWriter("demo.txt",true);
fw.write("abcde"); ?//在緩沖,沒寫到文件
fw.flush(); ? ? ? ?//刷新到文件
}?
catch (IOException e)?
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try?
{
if(fw!=null)
fw.close();
}?
catch (IOException e)?
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3. FileReader
FileReader fr = new FileReader("demo.txt");
fr.read(); ?讀一個節(jié)符,返回 -1 則表示讀完
char[] buf = new char[3];
fr.read(buf); ? //數(shù)據(jù)長3,所以讀3個字符后就不讀了
char[] buf1 = new char[3];
fr.read(buf1); ? //繼續(xù)讀下面的字符
4. 讀入字符數(shù)組
char[] buf = new char[1024];
int num = 0;
while((num=frr.read(buf)) != -1)
{
System.out.println(new String(buf,0,num));
}
frr.close();
5. BufferedWriter ?字符寫緩沖區(qū)
FileWrite fw = new FileWriter("buf.txt");
BufferedWriter bufw = new BufferedWriter(fw);
bufw.write("abcde");
bufw.newLine(); //寫入一個行分隔符
bufw.flush();
bufw.close();
6. BufferedReader ?//字符讀緩沖區(qū)
bufr.readLine(); ? ?//一次讀一行,但不包括換行符
FileReader fr = new FileReader("demo.txt");
BufferedReader bufr = new BufferedReader(fr);
String line = null;
while((line=bufr.readLine()) != null )
{
System.out.println(line); ?
}
bufr.close();
7. 裝飾設(shè)計(jì)模式
對原有對象的功能的增強(qiáng),要傳入一個對象
8. 裝飾與繼承的區(qū)別
MyReader
|--MyT
|--MyBufferT
|--MyM
|--MyBufferM
這樣,MyReader 類下每多一個子類,就要在子類上加一個MyBuffer
而裝飾類可以接收一個MyReader類型的對象,然后對這個對象進(jìn)行增強(qiáng)
9. LineNumberReader 類
setLineNumberReader(100); ? //設(shè)置第一行的行號為100,第二行為101....
getLineNumberReader(); ? ? ? 顯示行號
11. OutputStream ?寫,InputStream ?讀
FileOutputStream fos = new FileOutputStream("fos.txt");
fos.write("abcde".getBytes()); ?//不用flush,直接進(jìn)文件
fos.close();
FileInputStream fis = new FileInputStream("fos.txt"); ? //讀文件
byte[] a = new byte[5];
int ch = 0;
while((ch = fis.read(a)) != -1)
{
System.out.println(new String(a,0,ch));
picw.write(a,0,ch);
}
fis.available();
12. BufferedStream ?//字節(jié)讀寫緩沖區(qū)
BufferedInputStream bufis = new BufferedInputStream(new BufferedInputStream("c:/2.mp3"));
BufferedOutputStream bufis = new BufferedOutputStream(new BufferedOutputStream("c:/1.mp3"));
13. 讀取鍵盤錄入
BufferedReader bufw = new BufferedReader(new OutputStreamReader(System.in));
寫入鍵盤輸出
BufferedWriter bufw = new BufferedWriter(new OutputStreamWrite(System.out));
改變鍵盤錄入源
System.setIn(new FileInputStream("aa.java"));
System.setOut(new PrintStream("aa.java"));
PrintStream("aaa.txt"); ?把輸出信息輸入到文件
14. File?
File f = new File("file.txt");
f.createNewfile(); ? //沒有,則創(chuàng)建文件,有,則不創(chuàng)建
deleteOnExit();
f.delete();
f.canExecute(); ?//是否可執(zhí)行
f.exists() ? ?是否存在
f.mkdir ?//創(chuàng)建file.txt名的文件夾
f.mkdirs ?//創(chuàng)建多級文件夾
f.isFile(); ? 是不是文件
f.isDirectory(); ? ?是不是目錄
f.isHidden(); ? //是不是隱藏文件
f.isAbsolute(); ? ? 參數(shù)中的文件是不是絕對路徑,不管這個文件是否存在
f.getName();
f.getPath(); ? ?相對路徑包含文件名
f.getParent(); ? //參數(shù)中指定了絕對路徑,則返回絕對路徑(不包含文件名),否則為null
f.getAbsolutePath(); ? ? 絕對路徑包含文件名
f.lastModified(); ? 最后修改時間
f.length(); ? 大小
File f1 = new File("file1.txt");
f.renameTo(f1) ? 重命名,或移動文件
File[] files = File.listRoots();
for(File f : files){System.out.println(f);} ? //得到系統(tǒng)現(xiàn)有的盤符
File f = new File("c"\\");
String[] names = f.list();
for(String name : names ) { System.out.println(name); } ?//打印C盤下所有文件?
FilenameFilter ?是個接口類型 ,接口下只有一個方法
取download 目錄下的.txt
File dir = new File("D:/Download");
String[] arr = dir.list(new FilenameFilter()
{
public boolean accept(File dir,String name)
{
return name.endsWith(".txt");
}
}
);
for(String name : arr) {System.out.println(name);}
f.listFiles() ?//獲取文件夾下的文件對象
Properties ?hashtable 的子類。
Properties prop = new Properties();
File file = new File("count.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
int count=0;
String value = prop.getProperty("time");
if(value!=null)
count=Integer.parseInt(value);
count++;
prop.setProperty("time",count+"");
FileOutputstream fos = new FileOutputStream(file);
prop.store(fos,"");
fos.close();
fis.close();
PrintStream();
PrintWriter();
SequenceInputStream; ?合并流
切割文件
FileInputStream fis = new FileInputStream("c:\\1.bmp");
FileOutputStream fos = null;
byte[] buf = new byte[1024*1024];
int len=0;
int count =1;
while((len=fis.read(buf)) != -1 )
{
fos=new FileOutputStream("c:\splitfiles\\"+(count++)+".part");
fos.write(buf,0,len);
fos.close();
}
fis.close();
對象的持久化,把對象存在硬盤上
類 implements Serializable 才能被序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.class"));
oos.writeobject(new Person()); ?寫硬盤
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person1.class"));
oos.writeobject(new Person()); ?寫硬盤
ObjectInputStream
Person.Object
從硬盤上讀一個對象
ObjectInputStream oos = new ObjectInputStream("Person.class"); ??
Person p = (Person)ois.readObject(); ?讀硬盤?
Person p1 = (Person)ois.readObject(); ?讀硬盤?
public static final long serialVersionUID = 42L; ?自己定義UID,為了序列化方便
靜態(tài)是不能被序列化的
transient int age; transient 關(guān)鍵字修飾的 ?也不能被序列化
管道流
管道輸入流 ? 管道輸出流
PipedInputStream in = new PipedInputStream ();
PipedOutputStream out = new PipedOutputStream();
Read r = new Read(in); ? //線程類
Write w = new Write(out); ?//線程類
RandomAccessFile ?隨機(jī)訪問文件,只能操作文件。可讀,也可寫
r ?讀文件,文件不存在報(bào)異常
rw ?讀寫,文件若存在,不會覆蓋
RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
raf.write("李四".getBytes());
raf.write(97); ? 這里的97會變成 a ,碼表
RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
raf.read(buf); ?//讀
raf.seek(8); ? //調(diào)整對象中指針
可隨機(jī)讀,也可以隨機(jī)寫,如果所寫的指針上有數(shù)據(jù),則被覆蓋
DataStream ?操作基本數(shù)據(jù)類型的流對象
ByteArrayInputStream?
OutputStreamWriter ?轉(zhuǎn)換流,字節(jié)轉(zhuǎn)字符輸出到硬盤文件
InputStreamReader ? ? ? ? ? 字符文件輸入到內(nèi)存轉(zhuǎn)字節(jié)
十。網(wǎng)絡(luò)
1. 獲取IP地址
i1 = InetAddress.getByName("www.baidu.com");
System.out.println(i1.toString());
System.out.println(i1.getHostAddress());
System.out.println(i1.getHostName());
2. 獲取IP地址數(shù)組
InetAddress i1[] = InetAddress.getAllByName("www.baidu.com");
3. UDP 無連接,一次不能超過64K
發(fā)送數(shù)據(jù)包
DatagramSocket ds = null;
ds = new DatagramSocket(10000); ? //端口,不指定則隨機(jī)
byte[] buf = "udp ge men lai le".getBytes();
DatagramPacket dp = null;
dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("172.16.2.109"),1000);
ds.send(dp);
ds.close();
接收數(shù)據(jù)包
DatagramSocket ds = null;
ds = new DatagramSocket(10000);
while(true)
{
byte[] buf = new byte[1024];
DatagramPacket dp = null;
dp = new DatagramPacket(buf,buf.length);
ds.recive(dp);
String ip = ip.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
}
ds.close();
TCP ?面向連接--客戶端
Socket s = new Socket("192.168.1.254",10003);
OutputStream out = s.getOutputStream();
out.write("tcp ge men lai le ".getBytes());
byte[] buf = new byte[1024];
int len.read(buf);
System.out.println(new String(buf,0,len));
s.close();
TCP 服務(wù)端 ? //socket可關(guān)閉,可不關(guān)閉
ServerSocket ss = new ServerSocket(10003);
Socket s = ss.accept(); ? //接收客戶端數(shù)據(jù)
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
OutputStream out = s.getOutputStream();
out.write("Hello World!".getBytes());
s.close(); ?//關(guān)閉客戶端;
ss.close(); ?可選
4. URL ?
URL url = new URL("http://192.168.1.254/myweb/demo.html?name=haha&age=30");
int port = getPort();
if(port==-1)
port = 80;
System.out.println("getProtocol() :"+url.getProtocol());
System.out.println("getHost() :"+url.getHost());
System.out.println("getPort() :"+url.getPort()); ? ? ? ? ? ? ? //
System.out.println("getPath() :"+url.getPath());
System.out.println("getFile() :"+url.getFile());
System.out.println("getQuery() :"+url.getQuery());
5. URLConnection
URL url = new URL("http://192.168.1.254:8080/myweb/demo.html");
URLConnection conn = url.openConnection();
System.out.println(conn);
InputStream in = conn.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
來自 “ ITPUB博客 ” ,鏈接:http://blog.itpub.net/29798713/viewspace-1664440/,如需轉(zhuǎn)載,請注明出處,否則將追究法律責(zé)任。
轉(zhuǎn)載于:http://blog.itpub.net/29798713/viewspace-1664440/
總結(jié)
以上是生活随笔為你收集整理的Java 基础学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Git】git add
- 下一篇: java的reader_Java Rea