日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java学习笔记-基础篇

發(fā)布時間:2023/12/8 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java学习笔记-基础篇 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Java基礎(chǔ)篇

1—12 常識

13 this關(guān)鍵字

14參數(shù)傳遞

16 繼承

17 訪問權(quán)限

28—31異常

1—12 常識

1.文件夾以列表展示,顯示擴(kuò)展名,在地址欄顯示全路徑

2.javac編譯 java運(yùn)行

3.java開發(fā)環(huán)境?

java編輯器 ( integrated development environment) IDE? 集成開發(fā)環(huán)境

常見的Jbuilder、eclipse

4.double d1,d2,d3=0.123?? //不表示d1 d2 d3都是0.123

5.程序執(zhí)行過程中 對內(nèi)存的處理? 將內(nèi)存分成4個區(qū)域?code segment 、 data segment ?、stack ?、heap

print和println的區(qū)別??? println表示此處換行打印

shift+table鍵的使用 :批量修改縮進(jìn)/Alt+/開啟自動提示

代碼不夠健壯 只完成了功能 對于用戶輸入的很多情況沒有考慮

方法(method)中的return? 代表方法返回? 執(zhí)行到return 表示方法結(jié)束

屬性 attribute? 就是成員變量

哪些類 類的屬性和方法 類與類之間的關(guān)系

web service和soa? 究竟誰贏了(顯然是web service贏了)

約定俗稱的命名規(guī)則:

類名首字母大寫?? 方法名和變量名首字母小寫? 運(yùn)用駝峰標(biāo)識(每個單詞首字母大寫)

包命名方式?? package?? 公司名稱倒過來就行 com.xxx.test

訪問控制符 或者叫權(quán)限修飾符

繼承關(guān)鍵字? extends

?

人機(jī)交互方式:一種是通過圖形界面,一種是通過命令行(即cmd)

常用dos命令

dir

cd\? 回到根目錄

cd. . 回到上級目錄

md 文件名??? 新建目錄

cd? 目錄名??? 進(jìn)到指定目錄

Java兩大核心機(jī)制—JVM和GC,有了各平臺版本的JVM(如UNIX平臺版本、Linux平臺版本),java代碼在可以一次編譯,運(yùn)行在多個平臺上。

?

10%-3=1? 對負(fù)數(shù)取模可忽略不計(jì),結(jié)果仍為正

-10%3=-1? 被模的數(shù)為負(fù)數(shù),結(jié)果為負(fù)

-10%-3=-1

?

&&

||?? 短路與? 短路或? 如果前邊的判斷為真或?yàn)榧? 則后邊的不進(jìn)行判斷

?

從鍵盤讀取用戶輸入,使用Scanner類中的方法:

import java.util.Scanner;? 第一步導(dǎo)入Scanner類

public class TestScanner{

???????? public static void main(String[] args) {

?????????????????? Scanner scanner = new Scanner(System.in);?? 第二步聲明一個Scanner對象

?????????????????? System.out.println("Please enter number1");

?????????????????? int a;

?????????????????? a = scanner.nextInt();??? 第三步使用nextInt()方法

}

?

case 10:

case 9:

10和9這兩個標(biāo)簽,可以共用一個代碼塊

?

/*

*輸入2013年的某個月份和日期,例如month=4 day=21

*經(jīng)過程序計(jì)算,打印出輸入的月份和日期是2013年的第幾天

*TestSwitch.java

*/

?

System.out.println();?? //直接可以打印換行

?

break? continue的用法?

?

int[] a =null ?數(shù)組a的聲明

System.out.println(a.length)?? 在未分配內(nèi)存空間時 使用數(shù)組的屬性 會報空指針異常

a=new int[10]? 為數(shù)組a分配內(nèi)存空間

?

多維數(shù)組

int? t[][] = new int[4][]???

t[0] = new int[5]

t[1] = new int[3]

?

方法(即函數(shù))中,可以寫

return;

但是這行代碼之后的代碼都不會被執(zhí)行

?

類的實(shí)例化

Person p = new Person()

p1和p2是Person的兩個對象,操作任何一個的(非靜態(tài))成員變量都不會對另一個產(chǎn)生影響。

對象的生命周期:

?

?

匿名對象

new Person().shout();

出現(xiàn)在:只使用一次,經(jīng)常將匿名對象作為實(shí)參傳遞給一個函數(shù)調(diào)用。

?

信息的封裝和隱藏

將屬性聲明為私有的(private),再提供公開的(public) 方法:getXXX和setXXX方法來操作成員變量。

?

構(gòu)造器與類同名且沒有返回值(連void都沒有)。

?

方法的重載

在同一個類中允許存在多個同名的方法

方法名不同,返回值類型可以相同也可以不同,參數(shù)列表(個數(shù)或類型)不一樣。

?

13 this關(guān)鍵字

this是對調(diào)用當(dāng)前方法的那個當(dāng)前對象的引用

this的用途:指代的是當(dāng)前對象

1 在一般的方法中可以通過this來引用當(dāng)前對象的成員(方法、屬性)

2 通過this() 調(diào)用重載的構(gòu)造器,需要注意的是,這行代碼必須放在重載構(gòu)造器的第一行。

?

?

14參數(shù)傳遞

基本數(shù)據(jù)類型的參數(shù)傳遞和引用類型的參數(shù)傳遞? 兩者區(qū)分

?

16 繼承

extends關(guān)鍵字

注意:子類不能繼承父類私有(private)的成員和方法:不能直接訪問。

構(gòu)造器的繼承在Super關(guān)鍵字中講解。

?

17 訪問權(quán)限

Private? 僅在類的內(nèi)部訪問

Defalut? 僅在包的內(nèi)部訪問

Protected? 在子類中該屬性可以被訪問,可以跨包訪問

Public??? 訪問權(quán)限最高,無論是否在一個包內(nèi),是否是子類,都可以訪問

?

18 方法的重寫和覆蓋

?

28 異常

Java運(yùn)行過程中發(fā)生的異常事件可以分為兩類:

Error:JVM系統(tǒng)內(nèi)部錯誤(無能為力)

Exception:其他因編程錯誤或偶然的外在因素導(dǎo)致的一般性問題(可以避免),例如:

空指針

訪問不存在的文件

網(wǎng)絡(luò)異常

?

ArithmeticException:被除數(shù)為0的異常

ArrayIndexOutOfBoundsException:數(shù)組下邊越界異常

ClassCastException:類型轉(zhuǎn)換異常

NullPointerException:空指針異常,引用指向null,但是使用了這個引用的屬性或方法

?

Java采用異常處理機(jī)制,將異常處理的程序代碼集中在一起,與正常的程序代碼分開,使得程序簡潔易維護(hù)。

?

抓拋模型

拋出(throw)捕獲(catch)

一個異常回到main(),main()也不進(jìn)行處理的話,程序會中止

我們通常可以處理Exception,而對Error無能為力

?

29 處理異常

try....catch...finally...

在捕獲異常時 注意父類參數(shù)

可以有多個catch

問題:如果一個語句塊中有兩種異常,并且也寫了兩個catch來捕獲不同類型的異常,那么這兩個catch都會進(jìn)去嗎?還是,有多個catch的情況,只要有一個捕獲到了,后邊的catch都不進(jìn)去了?

finally語句始終會被執(zhí)行

?

運(yùn)行時異常和編譯時異常

IO異常屬于編譯時異常

?

30 聲明拋出異常

使用throws關(guān)鍵字聲明拋出異常(拋出即不做處理,由調(diào)用者處理)

throws方法拋出的異常可以是方法中出現(xiàn)的異常的類型或其父類類型

throws可以聲明拋出多個類型的異常,多個異常使用逗號分隔

運(yùn)行時異常不需要使用throws關(guān)鍵字聲明拋出

重寫方法不能拋出比重寫范圍更大的異常

?

31 人工拋出異常

使用throw關(guān)鍵字,人工手動拋出異常的步驟:

1 創(chuàng)建一個異常類對象

RuntimeException ex = new RuntimeException();

2 把異常類對象拋出去

throw? ex;

?

自定義的異常類:

1 通常繼承自RuntimeException(可以繼承Exception)

2 自定義的異常類就是用來被人工拋出的

?

32 Collection接口

1 創(chuàng)建一個Collection接口的對象

Collection collection = new ArrayList()

2 Collection重要方法說明

2.1 添加

collection.add(new Person())

Collection collection2 = new AyyayList()

collection2.add(new Person())

collection.addall(collection2)

System.out.println(collection.size())

?

2.2 用于訪問集合的方法:

獲取集合的長度:size()

對集合進(jìn)行遍歷的方法:iterator()可以得到對應(yīng)的Iterator接口對象

Iterator:迭代器

獲取Iterator接口對象

使用while循環(huán)和Iterator對象遍歷結(jié)合中的每一個元素,具體使用Iterator接口的hasNext()和nex() 方法

Iterrator iterator = collection.iterator()

while(iterator.hasNext()){

???????? Object obj = iterator.next();

???????? System.out.println(obj)

}

?

2.3 移除集合中的元素

remove():移除某一個指定的對象,通過equals()方法比較集合中是否存在該元素,以及是否能成功移除

removeAll()

clear():使集合中的元素置空

?

2.4 用于檢測集合的方法

retains()

retainsAll()

isEmpty()

?

2.5 其他方法

toArray()

T [] to Array(T[]):涉及到泛型,后面再講

equals():比較兩個集合是否相等

hashCode()

?

使用增強(qiáng)for循環(huán)的方式對集合進(jìn)行遍歷

for(Object obj:collection){

???????? System.out.println(obj)

}

?

33 Set接口

是collection的子接口,Set集合不允許包含相同元素,比較是否相同使用equals()

?

HashSet

1.1 基本特征

不能保證元素的排列順序

HashSet不是線程安全的

集合元素可以是null

對于HashSet:如果兩個對象通過equals() 方法返回true,這兩個對象的hashcode值也應(yīng)該相同

?

LinkedHashSet

按插入順序排序

?

34 ?TreeSet

自然排序和定制排序

自然排序

1 如果使用TreeSet()無參數(shù)的構(gòu)造器創(chuàng)建一個TreeSet對象,則要求放入其中的元素的類必須實(shí)現(xiàn)Comparable接口,所以,在其中不能放入null元素

2 必須放入相同類的對象,否則會發(fā)生類型轉(zhuǎn)換異常

3 兩個對象通過Comparable接口compareTo(Object obj)方法的返回值來比較大小,并進(jìn)行升序排序

4 當(dāng)需要把一個對象放入TreeSet中,重寫該對象對應(yīng)的equals()方法時,應(yīng)保證該方法與compareTo(Object obj)方法有一致的結(jié)果

?

定制排序

1 創(chuàng)建TreeSet對象時,傳入Comparator接口的實(shí)現(xiàn)類

Set set2 = new TreeSet(comparator); //comparator已經(jīng)實(shí)現(xiàn)了Comparator接口,并重寫了其中的compare方法

要求:Comparator接口的compare方法的返回值和兩個元素的equals()方法具有一致的返回值

?

35 ?List

list有序、可重復(fù)

以下為4種排序方法

?? ? //iterator遍歷

????? Iterator iterator = list.iterator();

????? while(iterator.hasNext()){

???????? System.out.println(iterator.next());

????? }

?????

????? //for增強(qiáng)遍歷

????? for(Object obj:list){

???????? System.out.println(obj);

????? }

????? //for遍歷

????? for(int i = 0 ; i < list.size(); i ++){

???????? System.out.println(list.get(i));

????? }

????? //ListIterator遍歷

????? ListIterator lit = list.listIterator();

????? while(lit.hasNext()){

???????? System.out.println(lit.next());

????? }

Arrays.asList(new Person("MM",30),new Person("NN",40))

?

36 Map

Key Value

Key不允許重復(fù)

//給map添加元素:put或put(map)

????? map.put("1", new Person("AA",12));

????? map.put("1", new Person("BB",25));

????? map.put("2", new Person("CC",36));

????? map.put("3", new Person("DD",42));

????? map.put("4", new Person("EE",68));

?????

????? /*

????? //從map中取出元素(遍歷)

????? //先取出鍵,再根據(jù)鍵取出值

????? Set keyset = map.keySet();

????? for(Object key:keyset){

???????? Object value = map.get(key);

???????? System.out.println(key + ":" + value);

????? }

?????

????? //直接取出值集合

????? Collection values = map.values();

????? for(Object val:values){

???????? System.out.println(val);

????? }

????? //直接取出鍵值對

????? for(Map.Entry<String, Object> entry:map.entrySet()){

???????? String key = entry.getKey();

???????? Object value = entry.getValue();

???????? System.out.println(key + ":" + value);

????? }

????? */

?????

????? //移除元素

????? map.remove("5");

?????

????? //工具方法:size() contains() isEmpty()

????? System.out.println(map.size());

????? System.out.println(map.containsKey("1"));

????? System.out.println(map.isEmpty());

?

37 Collections工具類和Enumeration

使用collections的sort方法對List中的元素進(jìn)行排序

Collections.sort(list, new Comparator(){

?

???????? public int compare(Object o1, Object o2) {

??????????? Person p1 = (Person) o1;

??????????? Person p2 = (Person) o2;

??????????? return p1.getAge() - p2.getAge();

???????? }

????? ?});

}

?

//獲取線程安全的List對象,使用synchronizedList()

List list2 = Collections.synchronizedList(new ArrayList());

//對Enumeration對象進(jìn)行遍歷

?????????????????? Enumeration names = Collections.enumeration(list);

?????

????? while(names.hasMoreElements()){

???????? Object obj = names.nextElement();

???????? System.out.println(obj);

????? }

?

38 泛型

不使用泛型的兩個問題:

1 放入集合中的可以是任何類型

2 取出時需要進(jìn)行強(qiáng)制類型轉(zhuǎn)換

使用泛型 可以解決這個問題 不是任意類型的list? 而是一個Person類型的list

List<Person> persons = new ArrayList();

?

Person [] personArray = persons.toArray(new Person[0]);

?

Map<String,Person> personMap = new HashMap<String,Person>();

????? personMap.put("111", persons.get(0));

????? personMap.put("222", persons.get(1));

????? personMap.put("333", persons.get(2));

????? personMap.put("444", persons.get(3));

????? personMap.put("555", persons.get(4));

?????

????? for(Map.Entry<String, Person> entry: personMap.entrySet()){

???????? System.out.println(entry.getKey() + ": " + entry.getValue());

????? }

?

39 定義泛型

public class Dao<T>{

??

?? public T get(Integer id){

????? T result = null;

????? return result;

?? }

??

?? public void save(T entity){

?????

?? }

}

?

40 繼承與泛型

String為Object類型的子類,則String[] 也是Object[] 的子類;

Object [] obj = new String[]{"11","22"};

但,String為Object類型的子類,List<String>并不是List<Object>的子類

List<String> strlist = Arrays.asList("AA","SS");

List<Object> objlist = strlist;??

//編譯時會提示cannot convert from List<String> to List<Object>

?

泛型通配符

????? List<Student> stus = new ArrayList<Student>();

????? stus.add(new Student("AA",12,"zhengdaUniversity"));

?????

????? printPersonInfo(stus);

?????

?? }

??

?? public static void printPersonInfo(List<? extends Person> persons){

????? for(Person person:persons){

???????? System.out.println(person);

????? }

?? }

?

41 泛型方法

把指定類型的數(shù)組中的元素放入到指定類型的集合中

泛型方法:在方法聲明時,同時聲明泛型,在方法的返回值,參數(shù)列表以及方法中都可以使用泛型類型

?

42 枚舉類

枚舉類:一個類的對象是有限且固定的;因此不能在類的外部創(chuàng)建類的對象;類內(nèi)部的屬性都是常量;在類的內(nèi)部創(chuàng)建對象,但需要在類的外部能夠訪問到該對象,而且不能被修改

private Season(String name,String desc){

????? this.name = name;

????? this.desc = desc;

?? }

?? private final String name;

?? private final String desc;

??

?? public static final Season SPRING = new Season("春天","春風(fēng)又綠江南岸");

?? public static final Season SUMMER = new Season("夏天","春風(fēng)又綠江南岸");

?? public static final Season FALL = new Season("秋天","春風(fēng)又綠江南岸");

?? public static final Season WINTER = new Season("冬天","春風(fēng)又綠江南岸");

?

也可以使用enum關(guān)鍵字來定義枚舉類

public enum Season2 {

?? //必須在枚舉類的第一行寫出有哪些枚舉值

?? SPRING("春天","春天好美啊"),

?? SUMMER("夏天 ","夏天很美"),

?? FALL("秋天","秋天很美"),

?? WINTER("冬天","冬天很冷");

?? private final String name;

?? private final String desc;

?

43 注解

@Override

@Deprecated

@SuppressWarnings

?

自定義Annotation

1 使用@interface定義注解

2 使用類似于接口方法聲明的方式來定義注解的屬性;其中返回值為屬性的類型,方法名為屬性的名稱

?

提取Annotation信息

在反射內(nèi)容時講解

?

44 ?IO

File類

public class IOTest {@Testpublic void testFile() throws IOException {//新建一個文件對象,該文件應(yīng)已被創(chuàng)建File file = new File("hello.txt");//訪問文件的名字String name = file.getName();System.out.println(name);//訪問文件的絕對路徑String path = file.getAbsolutePath();System.out.println(path);//將文件剪切到其他地方 // file.renameTo(new File("d:\\hello.txt"));//文件監(jiān)測相關(guān)方法 System.out.println(file.exists());File dir = new File("HaHa"); //新建目錄對象,該目錄應(yīng)事先已創(chuàng)建 System.out.println(dir.isFile());//獲取文件的常規(guī)信息 System.out.println(file.length());//文件操作File file2 = new File("abcd.txt"); //新建文件 file2.createNewFile();}}

?

?還可以通過mkDir()方法新建目錄

IO流的分類

InputStream&Reader

InputStream和Reader是所有輸入流的基類

@Testpublic void testInputStream() throws IOException {//創(chuàng)建一個字節(jié)輸入流InputStream in = new FileInputStream("hello.txt");//讀取文件內(nèi)容//.1讀取一個字節(jié),效率很低 -1表示讀到文件結(jié)尾 // int result = in.read(); // while(result != -1){ // System.out.print((char)result); // result = in.read(); // }//.2一次讀取一組字符byte [] buffer = new byte[10];int len = 8;//返回讀取的字節(jié)數(shù),若為-1表示讀到文件的結(jié)尾 // while((len = in.read(buffer)) != -1){ // //這樣讀 可能會出現(xiàn)錯誤 有可能最后不夠8個字符 for(byte b:buffer){ // //這樣讀可以避免以上錯誤 // for(int i = 0; i < len; i++){ // System.out.print((char)buffer[i]); // } // }//.3 把內(nèi)容讀取到字節(jié)數(shù)組的部分連續(xù)的元素中byte [] result = new byte[1024*10];//2表示讀取in這個字節(jié)流從頭開始的2個字符,result是被讀取后存放字節(jié)的數(shù)組,0表示從result的起始位置開始存放in.read(result, 0, 2);for(int i = 0; i < result.length; i++){System.out.print((char)result[i]);}
    
    in.close(); //關(guān)閉流文件
     
  }

?

@Testpublic void testReader() throws IOException {Reader reader = new FileReader("hello.txt");char[] buffer = new char[10];int len = 10;while((len = reader.read(buffer)) != -1){for(int i = 0 ;i < len; i++){System.out.print(buffer[i]);}}reader.close();}

OutputStream&文件復(fù)制

OutputStream和Writer,是所有輸出流的基類

@Testpublic void testOutputStream() throws IOException {//輸出字節(jié)流 abcd.txt應(yīng)已經(jīng)創(chuàng)建OutputStream out = new FileOutputStream("abcd.txt");//需要寫入的字符String content = "www.test.com.hahahahhahah.hahahah.hahahhahahhahahahahhahahahhahahah";byte[] buffer = new byte[10]; //這里的buffer只聲明了10個字節(jié),但發(fā)現(xiàn)可以容納任意字節(jié)//將字符轉(zhuǎn)換成字節(jié)buffer = content.getBytes();//下面的寫法也可以 // for(int i = 0 ; i < buffer.length; i++){ // out.write(buffer[i]); // } //直接這樣就可以寫入 out.write(buffer);//寫入一部分字符out.write(buffer, 0, 10);out.close(); }

?

/** 利用字節(jié)輸入輸出流,完成hello.txt文件的復(fù)制,將該文件復(fù)制為hello2.txt* 除文本文件外,還可以復(fù)制二進(jìn)制文件;字符流只能處理文本文件* */@Testpublic void testCopyFile() throws IOException {//.1創(chuàng)建定位到hello.txt的文件輸入流InputStream in = new FileInputStream("hello.txt");//.2創(chuàng)建定位到hello2.txt的文件輸出流OutputStream out = new FileOutputStream("hello2.txt");//.3創(chuàng)建一個byte數(shù)組,用于讀寫文件byte [] buffer = new byte[1024*10];int len = 0;//.4讀寫文件while((len = in.read(buffer)) != -1){out.write(buffer,0,len);}//.5關(guān)閉流資源 in.close();out.close();} 利用字符輸入輸出流,完成hello.txt文件的復(fù)制,將該文件復(fù)制為hello2.txt public class IOTest2 {
@Test
public void testCopyFile() throws IOException {//.1 聲明輸入輸出流Reader in = new FileReader("hello.txt");Writer out = new FileWriter("hello2.txt");//.2 創(chuàng)建一個字符數(shù)組char [] buffer = new char[10];//.3 利用循環(huán)讀取源文件,并向目標(biāo)文件寫入//.4 注意使用的寫入方法:write(cbuf, off, len)//而不能直接使用write(cbuf)int len = 0;//in.reader()返回讀取到的字符的個數(shù),到達(dá)結(jié)尾時返回-1while((len = in.read(buffer)) != -1){out.write(buffer, 0, len);}//.5 關(guān)閉流資源 in.close();out.close();} }

?

緩沖流

BufferedInputStream和BufferedOutputStream

BufferedReader和BufferedWriter

/** 復(fù)制hello.txt到hello3.txt*/@Testpublic void testBufferedReaderAndBufferedWriter() throws IOException{//.1 創(chuàng)建BufferedReader和BufferedWriterReader in = new FileReader("hello.txt");BufferedReader bufferedReader = new BufferedReader(in);Writer out = new FileWriter("hello3.txt");BufferedWriter bufferedWriter = new BufferedWriter(out);//.2 進(jìn)行讀寫操作String buffer = null;int i = 0 ; while((buffer = bufferedReader.readLine()) != null){ if (i != 0) { bufferedWriter.write("\n"); } bufferedWriter.write(buffer); i++; } //.3 關(guān)閉流:只需要關(guān)閉包裝流,節(jié)點(diǎn)流會會在內(nèi)部關(guān)閉 bufferedReader.close(); bufferedWriter.close(); }

?

/** 利用BufferedInputStream和BufferedOutputStream完成* hello.txt到hello4.txt的復(fù)制*/@Testpublic void testBufferedInputStreamAndBufferedOutputStream() throws IOException{InputStream inputStream = new FileInputStream("hello.txt");BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);OutputStream outputStream = new FileOutputStream("hello4.txt");BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);byte [] buffer = new byte[10];int len = 0 ;while((len = bufferedInputStream.read(buffer)) != -1){bufferedOutputStream.write(buffer, 0, len);}bufferedInputStream.close();bufferedOutputStream.close();}

?

轉(zhuǎn)換流

InputStreamReader和OutputStreamWriter

/** 利用轉(zhuǎn)換流InputStreamReader*/@Testpublic void testInputStreamReader() throws IOException{//指向文檔的字節(jié)流InputStream in = new FileInputStream("hello.txt");//把上面的流轉(zhuǎn)換為字符流Reader reader = new InputStreamReader(in);//把字符流轉(zhuǎn)換為帶緩沖的字符流BufferedReader bufferedReader = new BufferedReader(reader);String str = null;while((str = bufferedReader.readLine()) != null){System.out.println(str);}//關(guān)閉 in.close();reader.close();bufferedReader.close();}

?

/** 先創(chuàng)建兩個字節(jié)輸入輸出流:分別指向:hello.txt hello5.txt* 然后再轉(zhuǎn)為字符輸入輸出流* 再轉(zhuǎn)為帶緩沖的字符輸入輸出流* * 完成文件的復(fù)制*/@Testpublic void testOutputStreamWriter() throws IOException{InputStream in = new FileInputStream("hello.txt");OutputStream out = new FileOutputStream("hello5.txt");Reader reader = new InputStreamReader(in);Writer writer = new OutputStreamWriter(out);BufferedReader bufferedReader = new BufferedReader(reader);BufferedWriter bufferedWriter = new BufferedWriter(writer);String buffer = null;int i = 0;while((buffer = bufferedReader.readLine()) != null){if (i != 0) {bufferedWriter.write("\n");}bufferedWriter.write(buffer);i++;}bufferedReader.close();bufferedWriter.close();}

對象流

ObjectInputStream和ObjectOutputStream

.1)序列化需要實(shí)現(xiàn)Serializable接口

.2)類A下的某個字段是引用類型,引用的是類B,則類B必須實(shí)現(xiàn)Serializable接口,否則類A不能被序列化

在實(shí)際開發(fā)中,框架中已包含了此部分代碼,不需要我們自己寫

public class Person implements Serializable {/*** 類的版本號,用于對象的序列化,具體用于讀取對象時比對硬盤上對象的版本和* 程序中對象的版本是否一致,若不一致讀取失敗,并拋出異常*/private static final long serialVersionUID = 1L;

?

往硬盤文件寫內(nèi)容
@Test
public void testSerializable() throws IOException {Person person = new Person("Lily",26);OutputStream outputStream = new FileOutputStream("hello.txt");ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);objectOutputStream.writeObject(person);outputStream.close();objectOutputStream.close();}

?

從硬盤文件讀取
@Test
public void testOnjectInputStream() throws IOException, ClassNotFoundException {InputStream inputStream = new FileInputStream("hello.txt");ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);Object obj = objectInputStream.readObject();System.out.print(obj);objectInputStream.close();inputStream.close();}

?RandomAccessFile類

?RandomAccessFile及可以讀取文件內(nèi)容,也可向文件輸入內(nèi)容

@Testpublic void testRandomAccessFile() throws IOException {//.1創(chuàng)建一個RandomAccessFile對象RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt", "rw");//.3讀取文件內(nèi)容String str = null;while((str = randomAccessFile.readLine()) != null){System.out.println(str);}//設(shè)置指針位置,會覆蓋從指針開始位置的待增加字符串長度的字符randomAccessFile.seek(10);//.4向文件寫內(nèi)容 在文件結(jié)尾增加字符串randomAccessFile.writeBytes("append...");//.2關(guān)閉RandomAccessFile對象 randomAccessFile.close();}

?

/** 向hello.txt文件中插入一行:www.baidu.com* 插入到第二行,原內(nèi)容下移*/@Testpublic void testRandomAccessFile() throws IOException {RandomAccessFile access = new RandomAccessFile("hello.txt", "rw");//先讀一行String line = access.readLine();//這里有疑問,怎么能確保讀到buffer中的是除第一行之外的字符呢?又//沒有將指針定位到第一行結(jié)尾byte[] buffer = new byte[(int)(access.length()-line.length())];access.read(buffer);access.seek(line.length());//寫入要寫的字符access.writeBytes("\nHH\n");//再寫入先前的內(nèi)容 access.write(buffer);access.close();}

?

45 Java常用類

1 String是不可變的字符序列

2? 關(guān)于字符串緩沖池:直接通過=為字符串賦值,會先在緩沖池中查找有沒有一樣的字符串,如果有就把那個引用賦給字符串變量,否則,會創(chuàng)建一個新的字符串,并把它放入緩沖池

3 字符串的幾個常用方法:

3.1 去除前后空格的trim()方法

3.2 求子字符串的方法:subString()

從fromIndex開始,包含fromIndex,且String的字索引從0開始

3.3 subString(fromIndex,toIndex):[fromIndex,toIndex)

3.4 indexOf:求指定字符的索引

3.5 spilt(String regex):把字符串拆分成字符數(shù)組

3.6 equals():比較字符串內(nèi)容是否相等必須使用該方法,不能直接使用==

?

StringBuffer和StringBuilder

StringBuffer和StringBuilder是可以被修改的字符序列

append()方法:追加字符

注意:append()方法的返回值還是當(dāng)前的StringBuffer對象,可以使用方法的連綴

StringBuilder.append("a")

???????? ????? .append("b")

?????????????????? ? .append("c")

?

2). StringBuffer, StringBuilder 是可變的字符序列.

??? > StringBuffer 是線程安全的, 所以效率較低.

??? > StringBuilder 是線程不安全的, 效率較高. 大部分時使用 StringBuilder.

?

Date()封裝了日期和時間

1. DateFormat是一個抽象類

抽象類獲取對象的方式:

1) 創(chuàng)建其子類對象

2) 有的抽象類中提供了靜態(tài)工廠方法來獲取抽象類的實(shí)例

-SimpleDateFormat

??????? 如果需要把 Date 類型的對象格式化為一個字符串, 或把一個字符串轉(zhuǎn)為一個 Date 對象則使用 DateFormat.

???

??? //1. 調(diào)用靜態(tài)工廠方法來獲取 DateFormat 對象.

??? //傳入的參數(shù)是日期或時間的樣式.????

???????? DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,

?????????????????????????????????????????????? DateFormat.LONG);

???????????????????????????

???????? Date date = new Date();

???????? //格式化日期對象的 format 方法

???????? String dateStr = dateFormat.format(date);

???????? System.out.println(dateStr);

????????

???????? dateStr = "2013年6月10日 下午03時48分06秒";

???????? //解析字符串到日期對象的 parse 方法.

???????? Date date2 = dateFormat.parse(dateStr);

???????? System.out.println(date2);?

????????

???????? //創(chuàng)建 SimpleDateFormat 對象.

???????? DateFormat dateFormat =

???????????????????????????????????? new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");??

?

Random和Math

Random中封裝了隨機(jī)相關(guān)的方法:返回隨機(jī)的基本數(shù)據(jù)類型的值

Math:中封裝了常用的數(shù)學(xué)方法

?

小結(jié)

4. 集合:

1). Collection
①. List:
②. Set:

2). Map:
3). Iterator:
4). Collections, Arrays:

3. 泛型:

1). 在集合中使用泛型: List<Person> persons = new ArrayList<>();
2). 定義泛型類: class Dao<T, PK>{}. 在泛型類中可以像使用其他類型那樣使用泛型類型.
3). 泛型和繼承:
①. List<Object> 不是 List<Person> 的父類!
②. 通配符: List<? extends Object> list 可以指向 List<Object> 或 List<Person>
注意: 帶有通配符的泛型集合中不能添加除 null意外的任何元素.
4). 定義泛型方法: public static <E> E get(E e, Integer id){...}

2. IO:

1). 類:

InputStream FileInputStream BufferedInputStream ObjectInputStream
OutputStream FileOutputStream BufferedOutputStream ObjectOutputStream
Reader FileReader BufferedReader InputStreamReader
Writer FileWriter BufferedWriter OuputStreamWriter

2). 最常用的方法:

①. 文件的復(fù)制.

InputStream in = new FileInputStream(fileName);
OutputStream out = new FileOutputStream(fileName2);

byte [] buffer = new byte[1024 * 10];
int len = 0;

while((len = in.read(buffer)) != -1){
out.write(buffer, 0, len);
}

in.close;
out.close;

②.

BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));

3). 序列化:
①. 序列化的意義:
②. 如果需要對某個類的對象實(shí)現(xiàn)序列化: 則該類需要實(shí)現(xiàn) Serializable 接口. 且該類的所有字段也必須
是可被序列化的.

4). RandomAccessFile: 類中有一個指向文件內(nèi)容的指針. 通過 seek() 方法來移動指針.
可以完成對文件的讀寫操作.

1. 關(guān)于常用類:

1). String 是一個不可變的字符序列!
2). StringBuffer, StringBuilder 是可變的字符序列.
> StringBuffer 是線程安全的, 所以效率較低.
> StringBuilder 是線程不安全的, 效率較高. 大部分時使用 StringBuilder.
3). Date: 封裝了時間和日期.
4). DateFormat
-SimpleDateFormat
如果需要把 Date 類型的對象格式化為一個字符串, 或把一個字符串轉(zhuǎn)為一個 Date 對象
則使用 DateFormat.

//1. 調(diào)用靜態(tài)工廠方法來獲取 DateFormat 對象.
//傳入的參數(shù)是日期或時間的樣式.
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.LONG);

Date date = new Date();
//格式化日期對象的 format 方法
String dateStr = dateFormat.format(date);
System.out.println(dateStr);

dateStr = "2013年6月10日 下午03時48分06秒";
//解析字符串到日期對象的 parse 方法.
Date date2 = dateFormat.parse(dateStr);
System.out.println(date2);

//創(chuàng)建 SimpleDateFormat 對象.
DateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

5). Random & Math

?

46 反射

一般在框架中會使用到反射

有3種方式可以得到Class對象

/*** 關(guān)于Class:* 1.Class是一個類* 2.對象照鏡子后可以得到的信息,某個類的數(shù)據(jù)成員名、方法和構(gòu)造器* 某個類到底實(shí)現(xiàn)了哪些接口* 3.對于每個類而言,JRE都為其保留一個不變的Class類型的對象* 4.一個Class對象只能由系統(tǒng)建立對象* 5.一個類在JVM中只會有一個Class實(shí)例* @throws ClassNotFoundException * */@Testpublic void testClass() throws ClassNotFoundException{Class clazz = null;//1.得到Class對象//1.1直接通過類名.class的方式得到clazz = Person.class;//1.2 通過對象調(diào)用getClass()方法來獲取Person person = new Person();clazz = person.getClass();//1.3 通過全類名的方式獲取,用的較多String className = "com.test.lesson12.Person";clazz = Class.forName(className);}

?

/*** Class類的newInstance()方法* */@Testpublic void testNewInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException {String className = "com.test.lesson12.Person";Class clazz = Class.forName(className);//利用Class對象的newInstance()方法來創(chuàng)建類的一個對象//實(shí)際調(diào)用的是Person類的無參數(shù)的構(gòu)造器,在聲明類的時候無參數(shù)的構(gòu)造器是必要的//一般一個類若聲明了有參數(shù)的構(gòu)造器,還應(yīng)聲明一個無參數(shù)的構(gòu)造器Object obj = clazz.newInstance();}

?

?類加載器

@Testpublic void testClassLoader() throws ClassNotFoundException{String className = "com.test.lesson12.Person";//1.獲取一個系統(tǒng)的類加載器ClassLoader classLoader = ClassLoader.getSystemClassLoader();System.out.println(classLoader);//2.獲取系統(tǒng)類加載器的父加載器classLoader = classLoader.getParent();System.out.println(classLoader);//3. 獲取擴(kuò)展類加載器的父加載器classLoader = classLoader.getParent();System.out.println(classLoader);//4.測試當(dāng)前類由哪個類加載器進(jìn)行加載classLoader = Class.forName(className).getClassLoader();System.out.println(classLoader);//5.測試JDK提供的Object類由哪個類加載器負(fù)責(zé)加載classLoader = Class.forName("java.lang.Object").getClassLoader();System.out.println(classLoader);//6.關(guān)于類加載器的一個主要方法//調(diào)用getResourceAsStream獲得類路徑下的文件對應(yīng)的輸入流InputStream in = null;in = this.getClass().getClassLoader().getResourceAsStream("com/test/lesson12/test.properties");System.out.println(in);}

?method:

/*Class是一個對類的描述* Method:指定類中的方法* 1.獲取Method* 1.1獲取類的方法的數(shù)組:clazz.getDeclaredMethods()* 1.2獲取類的指定的方法:* clazz.getDeclaredMethod("setName", String.class)* 方法名 方法的參數(shù)類型列表* * 1.3通過method對象執(zhí)行方法:* Object obj = clazz.newInstance();method.invoke(obj, "設(shè)置的name");** */@Testpublic void testMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {String className = "com.test.lesson12.Person";Class clazz = Class.forName(className);//1.clazz對應(yīng)的Person類的方法,但不能獲取private方法Method[] methods = clazz.getMethods();for (Method method:methods) {System.out.println(method.getName());}//2.獲取類對象的所有方法,包括private方法,且只獲取當(dāng)前類聲明的方法Method[] methods2 = clazz.getDeclaredMethods();for (Method method:methods2) {System.out.println(method.getName());}//3.獲取指定的方法Method method = clazz.getDeclaredMethod("setName", String.class); //1個String類型的參數(shù) System.out.println(method);Method method2 = clazz.getDeclaredMethod("test"); //無參數(shù)的private方法 System.out.println(method2);Method method3 = clazz.getDeclaredMethod("setName", String.class,Integer.class);// 兩個參數(shù) System.out.println(method3);//4.執(zhí)行方法Object obj = clazz.newInstance();method.invoke(obj, "設(shè)置的name");}

?

?其余小節(jié)未細(xì)看:

3). 尚硅谷_佟剛_Java基礎(chǔ)_ 反射_獲取并執(zhí)行父類中定義的私有方法

4). 尚硅谷_佟剛_Java基礎(chǔ)_反射_使用 Method 的工具方法、

5). 尚硅谷_佟剛_Java基礎(chǔ)_ 反射_Field

47 線程

獲取當(dāng)前線程:Thread.currentThread().getName()

/** 1 在Java中,Thread類代表一個線程* * 2.實(shí)現(xiàn)線程有2種方式:* 2.1繼承Thread類* 2.2實(shí)現(xiàn)Runnable接口* * 3.繼承Thread類:* 3.1必須重寫run()方法,里邊放置的實(shí)際的線程體* * 4.啟動線程:* 4.1創(chuàng)建Thread對象* 4.2 調(diào)用Thread對象的start()方法啟動線程,而不是run()方法* * 5 實(shí)現(xiàn)Runnable接口的方式:* 5.1創(chuàng)建實(shí)現(xiàn)Runnable接口的實(shí)現(xiàn)類:必須實(shí)現(xiàn)run()方法* 5.2創(chuàng)建5.1對應(yīng)的Runnable接口的實(shí)現(xiàn)類對象* 5.3創(chuàng)建Thread對象,利用Thread(Runnable target)* 5.4 調(diào)用Thread類的start()方法啟動線程* * */public class threadTest {public static void main(String[] args) {Thread thread = new FirstThread();thread.start();String threadName = Thread.currentThread().getName();for (int i = 0; i < 100; i++) {System.out.println(threadName + ":" + i);}}}class FirstThread extends Thread{/*線程體在run()方法中*/@Overridepublic void run() {String threadName = Thread.currentThread().getName();for (int i = 0; i < 100; i++) {System.out.println(threadName + ":" + i);}} }

以下三種方式實(shí)現(xiàn):使用兩個線程共同打印1—100

/*不考慮線程安全的問題:* 使用Thread類,創(chuàng)建兩個線程,共同打印0——99* */public class PrintNumber {public static void main(String[] args) {int i = 0;MyThread thread1 = new MyThread("Thread1");MyThread thread2 = new MyThread("Thread2");MyThread.setI(i);thread1.start();thread2.start();}}class MyThread extends Thread{//給線程創(chuàng)建一個靜態(tài)參數(shù)private static int i;public static void setI(int i) {MyThread.i = i;}public MyThread(String threadName) {super(threadName);}@Overridepublic void run() {String threadName = Thread.currentThread().getName();for (; i < 100; i++) {System.out.println(threadName + ":" + i);}} }

?

public class PrintNumber2 {int i = 0 ;public static void main(String[] args) {PrintNumber2 printNumber = new PrintNumber2();MyThread2 thread1 = new MyThread2("thread1", printNumber);MyThread2 thread2 = new MyThread2("thread2",printNumber);thread1.start();thread2.start();}}class MyThread2 extends Thread{PrintNumber2 printNumber;public MyThread2(String threadName,PrintNumber2 printNumber) {super(threadName);this.printNumber = printNumber;}@Overridepublic void run() {String threadName = Thread.currentThread().getName();for (; printNumber.i < 100; printNumber.i++) {System.out.println(threadName + ":" + printNumber.i);}} }

?

public class MyRunnable implements Runnable {int i = 0;public void run() {String threadName = Thread.currentThread().getName();for (; i < 100; i++) {System.out.println(threadName + ":" + i);}}public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();Thread thread1 = new Thread(myRunnable);Thread thread2 = new Thread(myRunnable);thread1.start();thread2.start();}}

?線程的生命周期

New(新建狀態(tài)) Runnable(可執(zhí)行狀態(tài),有權(quán)獲得CPU控制權(quán),正在等待) Running(執(zhí)行狀態(tài),已獲得CPU控制權(quán))

Dead(死亡狀態(tài),使用isAlive方法判斷是否死亡,已經(jīng)死亡的線程不能再調(diào)用start()方法,否則會拋異常)

1)yield()方法 主動讓出CPU控制權(quán) 回到等待狀態(tài)?

2)sleep(int mills)方法 ?使線程休眠一段時間 以ms為單位

3)?join()方法 當(dāng)前線程調(diào)用其他線程的join方法,當(dāng)前線程將被掛起,進(jìn)入阻塞狀態(tài),等待另一個線程執(zhí)行完畢

4)interrupt() ?解除線程的阻塞狀態(tài) 會拋出InterruptedException

5)isAlive()?

?

線程調(diào)度

1)線程的優(yōu)先級

setPriority() (一般不使用這種方法來進(jìn)行優(yōu)先級設(shè)置)getPriority()

共有10個優(yōu)先級 整數(shù)值越大優(yōu)先級越高 每個線程都有1個默認(rèn)優(yōu)先級 主線程的優(yōu)先級是5

3個常量:MIN_Priority ?MAX_Priority ?NORM_Priority

線程同步

實(shí)現(xiàn)如下效果:

小強(qiáng) 拿走了1個蘋果
還剩下4個蘋果
小強(qiáng) 拿走了1個蘋果
還剩下3個蘋果
小明 拿走了1個蘋果
還剩下2個蘋果
小強(qiáng) 拿走了1個蘋果
還剩下1個蘋果
小強(qiáng) 拿走了1個蘋果
還剩下0個蘋果
小強(qiáng) 的線程結(jié)束了
小明 的線程結(jié)束了

public class ThreadTest2 implements Runnable {int appleNum = 5;public static void main(String[] args) throws InterruptedException {ThreadTest2 threadTest2 = new ThreadTest2();Thread th1 = new Thread(threadTest2);Thread th2 = new Thread(threadTest2);th1.setName("小強(qiáng)");th2.setName("小明");th1.start();th2.start();}boolean getApple(){//將以下代碼鎖起來,同一時刻只允許一個線程使用synchronized (this) {if(appleNum > 0){System.out.println(Thread.currentThread().getName() + " 拿走了1個蘋果");appleNum = appleNum - 1;System.out.println("還剩下" + appleNum + "個蘋果");return true;}return false;} } public void run() {while(appleNum > 0){getApple();} if(getApple() == false){System.out.println(Thread.currentThread().getName() + " 的線程結(jié)束了");}}}

線程安全問題

1)多個線程使用同一個資源導(dǎo)致,使用synchronized代碼塊(稱為同步塊)解決線程安全的問題

2)也可以使用synchronized 關(guān)鍵字定義方法,稱為同步方法

?

線程通信

1)wait()方法

2)notify() ?notifyAll()方法 喚醒等待中的線程 這些方法都需要在同步方法中調(diào)用

/** 張飛有1張20元鈔票 劉備和關(guān)羽各有1張5元鈔票 售貨員已有1張5元鈔票 票值5元* */public class TicketHouse implements Runnable{private int fiveCount = 1;private int twyCount;public synchronized boolean buyticket(){ //該方法使用synchronized修飾String buyerName = Thread.currentThread().getName();if("zf".equals(buyerName)){if(fiveCount < 3){System.out.println("張飛來買票了,當(dāng)前的五元鈔票已有" + fiveCount + "張,不夠找零,請您等待");try {wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("張飛來買票了,當(dāng)前的五元鈔票已有" + fiveCount + "張");fiveCount = fiveCount -3 ;twyCount = twyCount + 1;System.out.println("賣給張飛一張票,目前五元鈔票剩下" + fiveCount + "張;目前二十元鈔票有" + twyCount + "張");}else if("gy".equals(buyerName)){System.out.println("關(guān)羽來買票了,當(dāng)前的五元鈔票已有" + fiveCount + "張");fiveCount = fiveCount + 1;System.out.println("賣給關(guān)羽一張票,目前五元鈔票剩下" + fiveCount + "張");}else if("lb".equals(buyerName)){System.out.println("劉備來買票了,當(dāng)前的五元鈔票已有" + fiveCount + "張");fiveCount = fiveCount + 1;System.out.println("賣給劉備一張票,目前五元鈔票剩下" + fiveCount + "張");}if(fiveCount == 3){notifyAll(); //喚醒被暫停的線程,執(zhí)行wait()后的代碼 }return false;}public void run() {buyticket();}public static void main(String[] args) {TicketHouse ticketHouse = new TicketHouse();Thread th1 = new Thread(ticketHouse);Thread th2 = new Thread(ticketHouse);Thread th3 = new Thread(ticketHouse);th1.setName("zf");th2.setName("gy");th3.setName("lb");th3.start();th2.start();th1.start();}}

?48 網(wǎng)絡(luò)編程

目的:直接或間接地通過網(wǎng)絡(luò)協(xié)議與其他計(jì)算機(jī)進(jìn)行通訊

網(wǎng)絡(luò)編程中主要有兩個問題:

1)如何準(zhǔn)確地定位網(wǎng)絡(luò)上一臺或多臺主機(jī)

2)找到主機(jī)后如何可靠高效地進(jìn)行數(shù)據(jù)傳輸

常用的TCP/IP以其中的兩個協(xié)議:TCP和IP協(xié)議而得名,實(shí)際上是一組協(xié)議,還包括其他一些協(xié)議

傳輸控制協(xié)議TCP:先建立TCP鏈接,在傳輸完畢后,釋放連接

用戶數(shù)據(jù)包協(xié)議:UDP

端口號與IP地址和組合發(fā)出一個網(wǎng)絡(luò)套接字(Socket) 端口號被規(guī)定為一個16位的整數(shù)0—65535 ?

套接字能執(zhí)行7種基本操作:

—連接到遠(yuǎn)程主機(jī)

—綁定到端口

—接收從遠(yuǎn)程機(jī)器來的連接請求

—監(jiān)聽到達(dá)的數(shù)據(jù)

—發(fā)送數(shù)據(jù)

—接收數(shù)據(jù)

—關(guān)閉連接

@Testpublic void testInetAddress() {InetAddress inetAddress;try {//使用getByName()方法inetAddress = InetAddress.getByName("www.baidu.com");System.out.println(inetAddress);} catch (UnknownHostException e) {System.out.println("這個域名不存在");e.printStackTrace();}}

?

客戶端Socket的工作過程包括4個步驟:

1)創(chuàng)建一個Socket

2)打開連接到Socket的輸入/出流

3)按照一定協(xié)議對Socket進(jìn)行讀/寫操作

4)關(guān)閉Socket

服務(wù)端Socket的工作過程包含4個步驟:

1)調(diào)用ServerSocket(int port)創(chuàng)建一個服務(wù)器端套接字,并綁定到指定端口上

2)調(diào)用accept(),監(jiān)聽連接請求

3)調(diào)用Socket類的OutputStream和getInputStream獲取輸出流和輸入流,開始網(wǎng)絡(luò)數(shù)據(jù)的發(fā)送和接收

4)關(guān)閉Socket

Server端代碼:

@Testpublic void testServerSocket() throws IOException {ServerSocket serverSocket = new ServerSocket(8989);Socket socket = serverSocket.accept();OutputStream out = socket.getOutputStream();PrintWriter writer = new PrintWriter(out);writer.write("來自服務(wù)端的問候哦");writer.close();out.close();socket.close();serverSocket.close(); }

?客戶端代碼:

@Testpublic void testSocket() throws IOException {InetAddress address = InetAddress.getByName("127.0.0.1");Socket socket = new Socket(address, 8989);InputStream in = socket.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(in));System.out.println("O(∩_∩)O:" + reader.readLine());reader.close();in.close();socket.close();}

?完成將服務(wù)器文件復(fù)制到本地:

public class SocketTest {@Testpublic void testServerSocket() throws IOException {//新建一個ServerSocket,并設(shè)置監(jiān)聽請求ServerSocket serverSocket = new ServerSocket(8686);Socket socket = serverSocket.accept();//從程序到socket的輸出流OutputStream out = socket.getOutputStream();//buffer用于存放從文件中讀取出來的字符byte [] buffer = new byte[1024];int len = 0;//從文件到程序的輸入流InputStream in = new FileInputStream("abc.jpg");//通過in從文件讀入buffer,再從buffer通過out寫入socket,客戶端會通過socket接收while((len = in.read(buffer)) != -1){out.write(buffer, 0, len);}in.close();out.close();socket.close();serverSocket.close();}@Testpublic void testSocket() throws IOException {//客戶端新建一個socket并綁定端口InetAddress address = InetAddress.getByName("127.0.0.1");Socket socket = new Socket(address, 8686);//從socket到程序InputStream in = socket.getInputStream();//buffer用于存放從程序到本地文件byte [] buffer = new byte[1024];int len = 0 ;//從程序到本地文件OutputStream out = new FileOutputStream("abcd.jpg");//通過in從socket讀入buffer,再通過out將buffer寫入文件while((len = in.read(buffer)) != -1){out.write(buffer, 0, len);}in.close();out.close();socket.close();}}

?UDP:不能保證數(shù)據(jù)是否能送達(dá),也不能保證數(shù)據(jù)什么時候能送達(dá),所以不建議使用

?URL編程:

/** 將網(wǎng)絡(luò)資源下載到本地* */@Testpublic void testUrlConnection() throws IOException {URL url = new URL("http://127.0.0.1:8080/examples/test.txt");System.out.println(url.getPath());URLConnection urlConnection = url.openConnection(); //將文件下載到本地InputStream in = urlConnection.getInputStream();OutputStream out = new FileOutputStream("text.txt");byte [] buffer = new byte[1024];int len = 0;while((len = in.read(buffer)) != -1){out.write(buffer, 0, len);}}

?至此,java基礎(chǔ)篇結(jié)束。

轉(zhuǎn)載于:https://www.cnblogs.com/hnini/p/5328298.html

總結(jié)

以上是生活随笔為你收集整理的java学习笔记-基础篇的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。