JavaSE基础复习-2

一、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.");
			}
		}
	}
}


























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值