天天看點

JavaSE基礎複習-2一、Java之String類二、Math類三、File類四、容器五、流六、多線程七、網絡程式設計八、GUI程式設計

一、Java之String類

String類代表不可變的字元序列,每次改變都是重新建立一個新對象,丢棄原對象。 String常用構造方法: String s = "aaa"; String s = new String("aaa"); String s = new String(char[] value); String s = new String(char[] value,int offset,int count); String常用方法: public char charAt(int index) public int length(); public int indexOf(String str) public int indexOf(String str,int fromIndex) public boolean equalsIgnoreCase(String another) public String replace(char oldChar,char newChar) public boolean startsWith(String prefix) public boolean endsWith(String suffix) public String toUpperCase() public String toLowerCase() public substring(int beginIndex) public substring(int beginIndex,int endIndex) public String trim() public static String valueOf() //将基本資料類型轉換為字元串 StringBuffer類:代表可變的字元串 StringBuffer類常用構造方法: StringBuffer sb = ""; StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer(""); StringBuffer類常用構造方法: public StringBuffer append(String str) public StringBuffer append(StringBuffer sbuf) public StringBuffer append(char[] str) public StringBuffer append(char[] str, int offset,int len) public StringBuffer append(double d) public StringBuffer append(Object obj) public StringBuffer insert(int offset, String str) ... public StringBuffer delete(int start,int end) public int indexOf(Stirng str) public int indexOf(String str,int fromIndex) public String substring(int start) public String substring(int start,int end) public int length(0 public StringBuffer reverser() //用于将字元逆序

基本資料類型包裝類:封裝了一個相應的基本資料類型數值,并為其提供了一系列操作

二、Math類

提供了一系列靜态方法用于科學計算,其方法的參數和傳回類型一般為double類型 abs、acos、asin、atan、cos、sin、tan、sqrt、pow(double a,double b)、log、exp、max(double a,double b)、min(double a, double b) random()   //傳回0.0到1.0的随機數 long round(double a) //double型的資料a轉換為long類型 toDegrees(double angrad)  //弧度 --> 角度 toRadians(double angdeg) //角度 --> 弧度 取整:ceil,floor,round

三、File類

代表系統檔案名(路徑和檔案名) File的靜态屬性String separator儲存了目前系統的路徑分隔符 常見構造方法: public File(String pathname) public File(String parent, String child) 常用方法: public boolean canRead() public boolean canWrite() public boolean exists() public boolean isDirectory() public boolean isFile() public boolean isHidden() public long lastModified() public long length() public String getName() public String getPath()

public boolean createNewFile() throws IOException public boolean delete() public boolean mkdir() public boolean mkdirs() java.lang.Enum枚舉類型:隻能去特定值中的一個,使用enum關鍵字

四、容器

collection:set(HashSet),list(LinkedList,ArrayList) map:HashMap set:對象沒有順序且不可重複 list:對象有順序且可以重複 map:key-value映射對 常用方法: int size(); boolean isEmpty(); void clear(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator; boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); Object[] toArray(); 容器類對象在調用remove、contains等方法時需要比較對象是否相等,需要重寫equals和hashCode方法。 Iterator接口: Boolean hasNext() Object next() void remove(); List常用算法: sort(List)//排序 shuffle(List) //随機排序 reverse(List) //逆序排序 fill(List,Object) //用特定對象重寫整個List copy(List dest,List src) //複制 binarySearch(List,Object) //用二分法查找特定對象 實作排序需要實作comparable接口,comparaTo方法

五、流

常用流:DataInputStream、DataOutputStream、BufferedReader、BufferedWriter、FileInputStream、FileOutputStream、InputStreamReader、OutputStreamWriter、PrintWriter、PrintWriter、Object(需要實作序列化) 常用方法: InputStream: int read() throws IOException int read(byte[] buffer) void close() throws IOException OutputStream: void writer(int b) throws IOException void writer(byte[] b) void close() void flush() Reader: int read() int read(char[] cbuf) void close() BufferedReader: readLine() Writer: void writer(int c) void writer(char[] cbuf) void writer(String s) void close() void flush() BufferedWriter: newLine 檔案讀取:

import java.io.*;
public class TestFileInputStream
{
	public static void main(String args[])
	{
		long num = 0;
		int b = 0;
		FileInputStream in = null;
		try
		{
			in =  new FileInputStream("F:/Java/TestFileInputStream.java");
		}
		catch (FileNotFoundException e)
		{
			System.out.println("Can't find file.");
			System.exit(-1);
		}
		
		try
		{
			while((b = in.read()) != -1)
			{
				System.out.print((char)b);
				num ++;
			}
			in.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			System.exit(-1);
		}
		System.out.println();
		System.out.println("Have read: " + num);
	}
}
           

檔案寫入:

import java.io.*;
public class TestFileOutputStream
{
	public static void main(String args[])
	{
		FileInputStream in = null;
		FileOutputStream out = null;
		int b;
		try
		{
			in = new FileInputStream("f:/Java/HelloWorld.java");
			out = new FileOutputStream("f:/java/HW.java");
			while((b = in.read()) != -1)
			{
				//out.write((char)b);
				out.write(b);
			}
			in.close();
			out.close();
		}
		catch (FileNotFoundException e)
		{
			System.out.println("找不到HelloWorld.java");
			System.exit(-1);
		}
		catch (IOException e)
		{
			System.out.println("複制失敗");
			System.exit(-1);
		}
		System.out.println("複制成功");
	}
}
           

Object傳輸:

import java.io.*;

public class TestObjectIO {
	public static void main(String args[]) throws Exception {
		T t = new T();
		t.k = 8;
		FileOutputStream fos = new FileOutputStream("f:/java/testobjectio.dat");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(t);
		oos.flush();
		oos.close();
		
		FileInputStream fis = new FileInputStream("f:/java/testobjectio.dat");
		ObjectInputStream ois = new ObjectInputStream(fis);
		T tReaded = (T)ois.readObject();
		System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);
		
	}
}

class T 
	implements Serializable
{
	int i = 10;
	int j = 9;
	double d = 2.3;
	transient int k = 15;
}
           

六、多線程

通過Thread的執行個體建立新線程、通過run()方法完成線程操作、通過start()方法啟動線程。

建立線程: 實作Runnable接口 繼承Thread

基本方法: isAlive() //判斷線程是否終止 getPriority() //獲得該線程的優先級,範圍是1-10,預設是5 setPriority() //設定該線程的優先級 Thread.sleep() //目前線程睡眠多少毫秒 不解鎖對象 join() //調用某線程的方法 yield() //讓出CPU wait() //目前線程進入對象的wait pool(Object方法)解鎖對象 notify()/notifyAll() //喚醒wait pool中一個或所有等待線程(Object方法) 線程同步: synchronized互斥鎖:在同一時刻,隻能有一個線程通路該對象 鎖定對象:

synchronized(Object) {
...
}
           

鎖定方法:

synchronized public void method() {
..
}
           

七、網絡程式設計

TCP協定:需要建立連接配接、可靠、位元組流 UDP協定:不需要建立連接配接、不可靠、封包流、速度快 TCP端口和UDP端口分開,每個都有65536個 TCPClinet:

import java.io.*;
import java.net.*;

public class TalkClient
{
	public static void main(String args[])
	{
		try
		{
			Socket clinet = new Socket("192.168.1.144",8888);
			BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
			PrintWriter dos = new PrintWriter(new OutputStreamWriter(clinet.getOutputStream()));
			BufferedReader client_dis = new BufferedReader(new InputStreamReader(clinet.getInputStream()));
			boolean t = true;
			String s;
			while(t)
			{
				s = dis.readLine();
				dos.println(s);
				dos.flush();
				System.out.println("Client: " + s);
				s = client_dis.readLine();
				if(s.equalsIgnoreCase("close"))
				{
					t = false;
				}
				System.out.println("Server: " + s);
				
			}
			dos.close();
			client_dis.close();
			clinet.close();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
}
           

TCPServer:

import java.net.*;
import java.io.*;

public class TalkServer
{
	public static void main(String args[])
	{
		try
		{
			ServerSocket ss = new ServerSocket(8888);
			Socket so = ss.accept();
			BufferedReader dis = new BufferedReader(new InputStreamReader(so.getInputStream()));
			PrintWriter dos = new PrintWriter(new OutputStreamWriter(so.getOutputStream()));
			BufferedReader serDOS = new BufferedReader(new InputStreamReader(System.in));
			boolean t = true;
			String s;
			s = dis.readLine();
			System.out.println("Client: " + s);
			s = serDOS.readLine();
			while(t)
			{	
				dos.println(s);
				dos.flush();
				System.out.println("Server: " + s);
				if(s.equalsIgnoreCase("close"))
				{
					t = false;
				}
				s = dis.readLine();
				System.out.println("Client: " + s);
				s = serDOS.readLine();
				
			}
			dis.close();
			dos.close();
			ss.close();
			so.close();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
}
           

UDPClient:

import java.io.*;
import java.net.*;

public class UDPClient
{
	public static void main(String args[])
	{
		try
		{
			byte[] b = new Long(11256000L).toString().getBytes();
			DatagramPacket dp = new DatagramPacket(b,b.length,(new InetSocketAddress("192.168.1.144",5678)));
			DatagramSocket ds = new DatagramSocket(7890);
			ds.send(dp);
			ds.close();
		}
		catch(SocketException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
}
           

UDPService:

import java.net.*;
import java.io.*;

public class UDPServer
{
	public static void main(String args[])
	{
		try
		{
			byte[] b = new byte[1024];
			DatagramPacket dp = new DatagramPacket(b,b.length);
			DatagramSocket ds = new DatagramSocket(5678);
			while(true)
			{
				ds.receive(dp);
				System.out.println(new String(b,0,dp.getLength()));
			}
		}
		catch(SocketException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		
	}
}
           

八、GUI程式設計

Java圖形界面的最基本組成是Component,但一般不能獨立顯示,需要放在Contrainer中。 Contrainer是Component的子類。

常用Contrainer:Window、Panel

import java.awt.*;

public class TestPlane
{
	public static void main(String args[])
	{
		MyPanel mp = new MyPanel("MyFrame",300,300,500,500);
	}
}

class MyPanel
{
	MyPanel(String s,int m,int n,int x,int y)
	{
		Frame f = new Frame(s);
		f.setLayout(new FlowLayout());
		f.setBounds(m,n,x,y);
		f.setBackground(Color.blue);
		Panel p = new Panel();
		p.setSize(x/2,y/2);
		p.setBackground(Color.orange);
		f.add(p);
		f.setVisible(true);
	}
}
           

布局管理器: FlowLayout(Panel預設):預設從左到右,居中,間距為5。new FlowLayout(FlowLayout.RIGHT,20,40); new FlowLayout(); BorderLayout(Frame預設):分為東西南北中,預設為中,每個局域隻能加一個。南北水準縮放,東西隻能垂直縮放。 GridLayout:new GirdLayout(3,4);

事件監聽:

import java.awt.*;
import java.awt.event.*;

public class TestEvent
{
	public static void main(String args[])
	{
		Frame f = new Frame();
		Button b = new Button("click me!");
		TextField tf = new TextField();
		ButtonClick bc = new ButtonClick();
		TextFieldAL tfl = new TextFieldAL();
		b.addActionListener(bc);
		tf.addActionListener(tfl);
		tf.setEchoChar('*');
		f.add(b,BorderLayout.CENTER);
		f.add(tf,BorderLayout.SOUTH);
		f.pack();//自動調整大小
		f.setVisible(true);
	}
	
}

class ButtonClick implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
		System.out.println("Button is clicked.");
	}
}

class TextFieldAL implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
		TextField tf = (TextField)e.getSource();
		System.out.println(tf.getText());
		tf.setText("");
	}
}
           

滑鼠監聽:

import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class TestMouse
{
	public static void main(String args[])
	{
		new MyFrame();
	}
}

class MyFrame extends Frame
{
	ArrayList<Point> point = new ArrayList<Point>();
	MyFrame()
	{	
		setBackground(Color.blue);
		setSize(500,500);
		addMouseListener(new MouseE());
		setVisible(true);
	}
	
	public void paint(Graphics g)
	{
		Iterator i = point.iterator();
		while(i.hasNext())
		{
			Point p =(Point)i.next();
			g.setColor(Color.red);
			g.fillOval(p.x,p.y,10,10);
		}
	}
	
	public void addPoint(Point p)
	{
		point.add(p);
	}
}

class MouseE extends MouseAdapter
{
	public void mouseClicked(MouseEvent e)
	{
		MyFrame f = (MyFrame)e.getSource();
		Point p = new Point(e.getX(),e.getY());
		f.addPoint(p);
		f.repaint();
	}
}
           

鍵盤與視窗監聽:

import java.awt.*;
import java.awt.event.*;

public class TestKey
{
	public static void main(String args[])
	{
		new MyFrame();
	}
}

class MyFrame extends Frame
{
	//TextField tf = null;
	Label txt = null;
	MyFrame()
	{
	//	tf = new TextField(20);
		txt = new Label("no key has been pressed.");
	//	add(tf,BorderLayout.CENTER);
		add(txt,BorderLayout.NORTH);
		addWindowListener(new WindowE());
		addKeyListener(new KeyE());
		pack();
		setVisible(true);
	}
	
	class WindowE extends WindowAdapter
	{
		public void windowClosing(WindowEvent e)
		{
			setVisible(false);
			System.exit(-1);
		}
	}
	
	class KeyE extends KeyAdapter
	{	
		public void keyPressed(KeyEvent e)
		{
			
			if(e.getKeyCode() == e.VK_UP)
			{
				txt.setText("Key ''up'' has been typed.");
			//	System.out.println("dsd");
			}		
			
			else if(e.getKeyCode() == e.VK_DOWN)
			{
			//	System.out.println("das");
				txt.setText("Key ''down'' has been typed.");
			}
		}
	}
}