Java培訓第二週小結

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Collection;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Scanner;

import java.util.Set;


public class Test {

public static int ci = 0;  //定義次數


public static void xitong() {

String path = "C:\\Users\\lenovo\\Desktop\\Test.txt";//文件路徑

File file = new File(path);

file.delete();//刪除原來文件

File parentFile = file.getParentFile();//得到上一級文件夾

if(!parentFile.exists())

{

parentFile.mkdirs();//創建當前文件夾,以及父路徑不存在的文件夾

}

if(!file.exists())

{

try

{

file.createNewFile();//創建一個空文件

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

User[] user = new User[6];//客戶數組

user[0] = new User("admin", "admin123", "11111111111");

user[1] = new User("ABC", "abcabc", "11111111111");

user[2] = new User("BCD", "bcdbcd", "11111111111");

user[3] = new User("CDE", "cdecde", "11111111111");

user[4] = new User("DEF", "defdef", "11111111111");

user[5] = new User("EFG", "efgefg", "11111111111");

for (int i = 0; i < user.length; i++) {

writer(user[i], path);//將客戶信息寫入文件

}

ZhuJieMian jieMian = new ZhuJieMian();

boolean m = false;

while(!m)

{

jieMian.denglu();//輸出想要的字符串

Scanner scan = new Scanner(System.in);

int i = scan.nextInt();//選擇功能

while (!(i == 1 || i == 2 )) 

{

System.out.println("輸入錯誤,請重新輸入!");

i = scan.nextInt();

}

switch (i) 

{

case 1:

ZhuCe ce = new ZhuCe();//註冊類

writer(ce.zhuce(), path);

m = false;

break;

case 2:

boolean b = true;

Scanner scan1 = new Scanner(System.in);

A:while (b)

{

DengLu(path, scan, scan1,file);//登陸方法

}


break;

default:

break;

}

}

}

private static void DengLu(String path, Scanner scan, Scanner scan1,File file) {

System.out.println("請輸入用戶名:");

String inputStr = scan1.nextLine();

FileReader fr = null;

StringBuffer buffer = null;

try

{

fr = new FileReader(path);

int len = 0;

char[] cbuf = new char[500];

buffer = new StringBuffer();

while(-1 != (len  = fr.read(cbuf)))

{

buffer.append(new String(cbuf,0,len));//將文件中的字符串寫入buffer

}

} catch (FileNotFoundException e)

{

e.printStackTrace();

} catch (IOException e)

{

e.printStackTrace();

}

String[] read = buffer.toString().split(";");//將buffer分解成數組

String[][] read1 = new String[read.length][];

for (int j = 0; j < read1.length; j++) {

read1[j] = read[j].split(",");

}

HashMap<String, User> hashMap = new HashMap<>();

for (int j = 0; j < read1.length; j++) {

hashMap.put(read1[j][0], new User(read1[j][0], read1[j][1], read1[j][2]));//將客戶信息寫入hashMap容器

}

if(hashMap.get(inputStr) != null)

{

System.out.println("請輸入密碼:");

String inputStr1 = scan1.nextLine();

if(inputStr1.equals(hashMap.get(inputStr).password))//判斷密碼

{

if(inputStr1.equals("admin123"))//當客戶名爲管理員的用戶名

{

boolean d = true;

while(d)

{

System.out.println("用戶信息:");

Collection<User> values = hashMap.values();

// 第一種

// 獲取map中保存key的容器

Set<String> keySet = hashMap.keySet();

Iterator<String> iterator = keySet.iterator();

while(iterator.hasNext())

{

String key = iterator.next();

User valus = hashMap.get(key);

if(valus.user_name.equals("admin"))

{

continue;

}

System.out.println("用戶名: "+valus.user_name+",密碼: "+valus.password+",電話: "+valus.tel);

}

System.out.println("你可以選擇刪除功能,確認請輸入1,輸入2返回上一級,其他輸入退出系統!");

String j = scan.next();

if(j.equals("1"))

{

boolean c = true;

while(c)

{

System.out.println("請輸入你要刪除用戶的用戶名:");

String string1 = scan.next();

if(hashMap.get(string1) != null)

{

hashMap.remove(string1);

c = false;

}else

{

System.out.println("輸入錯誤,請重新輸入!");

}

}

}else if(j.equals("2"))

{

d = false;

}else 

{

System.out.println("感謝您應用本系統,再見!");

file.delete();

}

}

}else

{

System.out.println("登錄成功!");

file.delete();

}

}

else

{

System.out.println("輸入錯誤,請重新輸入!");

}

}else

{

System.out.println("輸入錯誤,請重新輸入!");

}

}

public static void writer(User user,String path) //將客戶信息寫入文件

{

String str = user.toString();

FileWriter fw = null;

try

{

   fw = new FileWriter(path,true);

   fw.write(str);

   fw.flush();

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}finally

{

if(fw != null)

{

try

{

fw.close();

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

這是一個用戶登錄註冊的作業,雖然看是簡單,當時需要一定的java基礎和邏輯能力,我們需要不斷練習,熟練代碼。

StringBuffer  代表可變的字符序列

     //構造方法

StringBuffer buffer = new StringBuffer();//默認16
  StringBuffer buffer1 = new StringBuffer("123");//字符串長度+16
  StringBuffer buffer2 = new StringBuffer(20);//設置長度
 
  buffer1.append(123).append(12.4).append(true).append("asd");
  //如果添加的數據超出緩衝區的長度,他會自動擴充,擴充的長度爲原長度的兩倍+ 2
  System.out.println(buffer1.toString());
  //StringBuffer特有的,對StringBuffer立面保存的字符進行操作,但是不會產生新的對象
  buffer1.insert(1, "=====");
  System.out.println(buffer1.toString());
  buffer1.delete(2, 5);//包左不包右
  System.out.println(buffer1.toString());
  buffer1.reverse();//反向字符串
  System.out.println(buffer1.toString());
  buffer1.replace(0, 5, "++++");//包左不包右
  System.out.println(buffer1.toString());
  //跟字符串類似
  System.out.println(buffer1.capacity()+ "1");//空間長度
  System.out.println(buffer1.length() + "a");
  buffer1.setLength(10);
  System.out.println(buffer1.capacity()+ "2");
  System.out.println(buffer1.length() + "b");//實際字符長度
  System.out.println(buffer1.toString());
  System.out.println(buffer1.charAt(5));

Character  靜態方法:


isDigit(char ch) 判斷是否是數字
isLetter(char ch)  判斷是否字母
isLowerCase(char ch) 
          確定指定字符是否爲小寫字母。
isUpperCase(char ch) 
          確定指定字符是否爲大寫字母。

單實例模式   單態模式  SingleTon

步驟:

1、私有化構造方法

2、聲明一個private final static 的成員變量,類型爲當前類型,去實例化一個當前類型的對象。

3、聲明一個public static的方法用戶獲取當前類型的成員變量

異常捕獲:

   try{

       //可能出現異常的地方,

   }catch(Exception e)

{

     System.out.println(e.getMessage());//得到異常信息

   e.printStackTrace();//打印異常棧信息 
}

Exception

        RuntimeException 運行時異常

                   運行時出現的錯誤 ,而且這類異常出現的概率比較高,所以一般我們是不會去捕獲

           常見運行時異常:

                 ArithmeticException 數學運算異常

                 NullPointerException  空指針異常

                 StringIndexOutOfBoundsException  字符串索引越界

                 ArrayIndexOutOfBoundsException   數組下標越界

                 NegativeArraySizeException    數組定義異常

                 IllegalArgumentException 非法參數異常


           注意: 不需要try{}catch(){}捕獲,要看的懂異常的原因,通過修改代碼區捕獲它。

Check Exception 檢查異常

             在語法上需要去捕獲 

             IOException


try{}catch(){}catch(){}

 try之後可以有多個catch  但是要保證catch之後捕獲的異常類型要有一定的順序(子類在上父類在下)


finally  在catch之後:不管try中代碼有沒有出現錯誤都必須執行

throws   

   在方法之後聲明調用該方法可能拋出某種異常,可以聲明拋出多個。

   RuntimeException可以不用聲明被捕獲

throw 

   throw在具體的某個位置拋出某個異常,一旦被執行,以下的代碼就結束。

     但是可以用try{}catch(){}直接捕獲

重寫中方法異常拋出的聲明:

1、重寫是可以不聲明拋出異常

2、重寫方法不可以拋出被重新方法聲明之外的異常(運行時異常除外)

自定義異常:

 使用自定義異常一般有如下步驟:

1、通過繼承 java.lang.Exception 類聲明自己的異常類。

2、在方法適當的位置 生成自定義異常的實例,並用throw 語句拋出。

3、 在方法的聲明部分用throws 語句聲明該方法可能拋出的異常。

Set 接口

  無序不可重複

 無序:不按照添加先後,添加完之後有一定的順序

  Set接口沒有新增的方法,所有的放都是Collection繼承過來的。

主要實現類:

     HashSet

         順序:按hash碼排列

List接口

    有順序可以重複

     F838BAE70D214A818A943D43512856DA

     主要實現類:

           ArrayList

          LinkedList

list新增了

 remove(int index)//移除索引的元素

 remove(Object o)//具體的元素

Iterator  迭代器

  Collection接口 有聲明 iterator() 方法

1D793B2A88A54142AE32E05F06651286

ArrayList中 :

  toArray()  把容器裏面的元素轉換成數組裏面的元素

  toArray(T[] t)聲明一個數組,然後把容器裏面的元素按照原來順序賦值到數組當中


removeRange(int fromIndex, int toIndex)
          移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之間的所有元素。(包級)

注意: ArrayList中的常用API要熟練

容器:

LinkedList

    


addFirst(E e)
          將指定元素插入此列表的開頭。
addLast(E e)
          將指定元素添加到此列表的結尾。
pop()
          從此列表所表示的堆棧處彈出一個元素。
push(E e)
          將元素推入此列表所表示的堆棧。

Map

    key - value  保存數據

1、key是不可以重複

2、value是可以重複的

HashMap

40C3B50F84114631991525DA119E1AB6

hashmap數據添加是無序

  按照key的hashcode排序

 作爲key的類型,必須重寫hashcode  equlse

map遍歷

// 第一種

// 獲取map中保存key的容器

  Set<String> keySet = hashMap.keySet();

  Iterator<String> iterator = keySet.iterator();

  while(iterator.hasNext())

  {

   String key = iterator.next();

   String valus = hashMap.get(key);

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

  }

 

  //第二種

  Set<Entry<String, String>> entrySet = hashMap.entrySet();

  Iterator<Entry<String, String>> iterator1 = entrySet.iterator();

  while (iterator.hasNext())

  {

   Entry<String, String> next = iterator1.next();

   String key = next.getKey();

   String value = next.getValue();

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

  }

//建議使用第一種

工具類:

Arrays    數組的工具類

9DB58CADB7B34D99A3130188DE152ADC

Collections

    0B95ED6B7AA24C81AED0E1A76134B826

Comparable  //讓實現這個接口的對象具有比較大小的能力

Compartor  //比較者 



9D959899D7AE46E9841A3D6FA34B184A

File

   抽象路徑   C: + File.separator + java + File.separator  + day01


 絕對路徑 E:\FA01

 相對路徑: \day01

CE7F4ECA85D442FD97E3ACD4B9058149

//文件過濾器接口

class MyFilter implements FilenameFilter

{

 public boolean isPPt(String name)

 {

  if(name.toLowerCase().endsWith(".ppt") || name.toLowerCase().endsWith(".pptx"))

  {

   return true;

  }

  return false;

 }

 @Override

 public boolean accept(File dir, String name)

 {

  return isPPt(name);

 }

 

}

字節流:

  節點流:

  FileInputStream

  FileOutPutStream

  注意: 一般都去讀取圖片、文件

  

  處理流: 套在其他節點流或者處理流之上的流

    緩存流  BufferedOutputStream   (前提:節點流存在  只是性能上面有所提升)


字符流: 讀文本

  節點流

  FileWriter  字符輸出流

  FileReader  字符輸入流

  

   處理流:

     緩存流  BufferedReader   新增readLine() 一次讀取一行,如果到末尾就返回null  

         BufferedWriter    新增 newLine()  換行


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章