java学习笔记(一)

List使用

List lst = new ArrayList();//List是接口,ArrayList是实现类

list.add("hello");//添加

list.removeAt(0);//删除

list.get(0);//获得

Int32[] vals = (Int32[])list.toArray(typeof(Int32));//转换成数组

String[] attr = (String[])list.toArray(new String[list.size()]);//

//遍历foreach

List<String> lst = new ArrayList<String>();//泛型

lst.add("aaa");//.......

for (String str: lst) {....}

list1.addAll(list2);//连接list2到list1

//数组转成list

List lst = Arrays.asList("a","b","c");

String[] arr = new String[]{"hell","worl","hah"};

List lst = Arrays.asList(arr);

常用集合类的继承关系

Collection<--List<--Vector 

Collection<--List<--ArrayList 

Collection<--List<--LinkedList 

Collection<--Set<--HashSet 

Collection<--Set<--HashSet<--LinkedHashSet 

Collection<--Set<--SortedSet<--TreeSet 

Map<--SortedMap<--TreeMap 

Map<--HashMap 

HashSet使用

Set<Object> set = new HashSet<Object>();

set.add(obj);

Iterator<Object> it = set.iterator();

while (it.hasNext()) obj = it.next();

Queue使用

Queue<String> que = new LinkedList<String>();

que.offer("hello");//入队列

while (que.poll() != null);//出队列

que.size();//队列大小

线程安全队列实现:http://blog.csdn.net/madun/article/details/20313269

socket对象发送接收实例

import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String pwd;

public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPwd() {
return this.pwd;
}
}

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ObjSend {
public static void main(String[] args) {
new ObjSend().start();
}
public void start() {
try {
Socket socket = new Socket("127.0.0.1", 7777);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
User user = new User();
user.setId(1);
user.setName("xiaoming");
user.setPwd("123456");
oos.writeObject(user);
oos.flush();
oos.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class ObjRecv {
public static void main(String[] args) {
new ObjRecv().start();
}
public void start() {
try {
ServerSocket ss = new ServerSocket(7777);
while (true) {
System.out.println("start to accept...");
Socket socket = ss.accept();
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
Object obj = ois.readObject();
if (obj != null) {
User user = (User)obj;
System.out.println("id: " + user.getId());
System.out.println("name: " + user.getName());
System.out.println("password: " + user.getPwd());
}
ois.close();
socket.close();
}
// ss.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

socket udp实例

import java.net.*;
public class UdpSend {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
byte[] buf = "UDP Demo".getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);
ds.close();
System.out.println("data send ok!");
}
}

import java.net.*;
public class UdpReceive {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp =new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(), 0, dp.getLength());
int port = dp.getPort();
System.out.println(data + ":" + port + "@" + ip);
ds.close();
}
}

读文件实例

public class FileRead {
public void readFile(String path) {
try {
String encoding = "UTF-8";
File file = new File(path);
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufReader = new BufferedReader(read);
String line = null;
while ((line = bufReader.readLine()) != null) {
System.out.println(line);

Thread.sleep(2000);//休眠2秒

}
} else {
System.out.println("file not exist.");
}
} catch (Exception e) {
System.out.println("read file error.");
}
}
public static void main(String[] args) {
new FileRead().readFile("test.txt");
}
}

MessageFormat例子

public class DataParser
{
public OsInfo parseToOsInfo(String str)
{
OsInfo info = new OsInfo();
MessageFormat format = new MessageFormat("{0,number,0};{1,number,0};{2}");
try
{
Object[] results = format.parse(str);
info.setCpu(((Number)results[0]).intValue());
info.setMem(((Number)results[1]).intValue());
String tasksBuf = (String)results[2];
String[] tasks = tasksBuf.split(",");
info.setTasks(tasks);
} catch (ParseException e)
{
e.printStackTrace();
return null;
}
return info;
}
}

 

时间戳例子

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
public class CurrentTime {
    public static void main(String[] args) {
        long timestamp = System.currentTimeMillis();
        System.out.println(timestamp);
        System.out.println(Calendar.getInstance().getTimeInMillis());
        System.out.println(new Date().getTime());
        String str = String.format("%tF %<tT", timestamp);
        System.out.println(str);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(sdf.format(new Date()));
        System.out.println(sdf.format(new Date(timestamp - 5000)));
    }
}

 获得类名

import java.util.Map;
import java.util.HashMap;
public class MyTest2 {
    public static void main(String[] args) {
        MyTest2 a = new MyTest2();
        Class c = a.getClass();
        System.out.println(c.getName());
        Map map = new HashMap();
        System.out.println(map.getClass().getName());
    }
}

 编译utf-8编码的源文件

转换成无BOM的utf8格式

javac -encoding utf8 Test.java -d .

java com.aaa.sample.Test

map使用

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class MapTest {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put("item0", "value0");
        map.put("item1", "value1");
        map.put("item2", "value2");
        map.put("item3", "value3");
        map.put("item4", "value4");
        map.put("item5", "value5");
        Set set = map.entrySet();
        Iterator it = set.iterator();
        while (it.hasNext()) {
            Map.Entry mapentry = (Map.Entry)it.next();
            System.out.println(mapentry.getKey() + "/" + mapentry.getValue());
        }
        System.out.println(map.get("item4"));
        System.out.println(map.get("item7"));
    }
}

 

//遍历map

for(String key: map.keySet()){value=map.get(key);}
for(Entry<String,Object> entry: Map.entrySet()){key=entry.getKey();value=entry.getValue();}

应用第三方类库的编译运行

import com.google.gson.Gson;
public class JsonTest {
    public static void main(String[] args) {
        System.out.println("json test");
        Gson gson = new Gson();
        Person p = new Person("aaa", 12);
        String str = gson.toJson(p);
        System.out.println(str);
    }
}
class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

编译:javac -classpath ./gson-2.2.4.jar JsonTest.java

运行:java -classpath .;./gson-2.2.4.jar JsonTest

字符串操作

String[] array = str.split("\\.");
str.substring(0, str.indexOf('.'));
str.contains(".");

文件内容追加

//append1
FileOutputStream out = new FileOutputStream("f:/out.txt", true);
PrintStream p = new PrintStream(out);
p.println("hello");
p.println("world");
out.close();
p.close();
//append2
FileWriter fw = new FileWriter("mydata.txt",true);
PrintWriter out = new PrintWriter(fw);
out.println("你好!");
out.close();
fw.close();

 根据类名创建类

Class c = Class.forName("org.abc.test.Person");
Object o = c.newInstance();
Person p = (Person)o;

对象克隆

class CloneClass implements Cloneable {
    private int a;
    public CloneClass clone() {
        CloneClass o = null;
        try {
            o = (CloneClass)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return o;
    }
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
}

 

posted @ 2014-11-25 17:22  feilv  阅读(275)  评论(0编辑  收藏  举报