JFrame frame=new JFrame();
JButton button=new JButton("click me");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Box implements Serializable{
private int height;
private int width;
public void setHeight(int height){
this.height=height;
}
public void setWidth(int width){
this.width=width;
}
public static void main(String[] args){
Box box=new Box();
box.setHeight(20);
box.setWidth(40);
ObjectOutputStream os=null;
FileOutputStream fs=null;
try{
fs = new FileOutputStream("./testfile/foo.ser");//是以demo6(IO)为当前路径
os=new ObjectOutputStream(fs);
os.writeObject(box);
}catch(FileNotFoundException ex){
ex.printStackTrace();
}catch( IOException ex){
ex.printStackTrace();
}finally{
try{
os.close();
fs.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
}
//可序列化对象
import java.io.Serializable;
public class GameCharater implements Serializable{
private String name;
private String type;
private transient String coloth;
public GameCharater(){
}
public GameCharater(String name,String type,String coloth){
this.coloth=coloth;
this.name=name;
this.type=type;
}
public String getName(){
return name;
}
public String getType(){
return type;
}
public String getColoth(){
return coloth;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
//序列化对象的序列和解xulie
public class GameSave1 {
private static int num=0;
public static void main(String[] args){
GameCharater gc1=new GameCharater("张三", "战士", "black");
GameCharater gc2=new GameCharater("李四", "射手", "red");
GameCharater gc3=new GameCharater("王", "法师", "blue");
GameSave1 gs=new GameSave1();
ArrayList<GameCharater> glist=new ArrayList<GameCharater>();
glist.add(gc1);
glist.add(gc2);
glist.add(gc3);
gs.outPutStream("./testfile/game.ser", glist);
gc1=null;
gc2=null;
gc3=null;//设为null就无法取到堆上的对象了
gs.inputStream("./testfile/game.ser");
}
public void inputStream(String path){
ObjectInputStream os=null;
try{
os=new ObjectInputStream(new FileInputStream(path));
for(int i=0;i<GameSave1.num;i++){
GameCharater gc=(GameCharater)os.readObject();
System.out.println("姓名"+gc.getName());
System.out.println("颜色"+gc.getColoth());
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void outPutStream(String path,ArrayList<GameCharater> gl){
try{
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(path));
for(GameCharater g:gl){
num++;
os.writeObject(g);
}
os.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
objectOutputStream.writeObject(对象)
FileWriter writer=new FileWriter(路径);
fileWriter.write("字符串");
import java.io.File;
import java.io.IOException;
public class MyTest {
public static void main(String[] args){
try{
File f=new File("./testfile");
if(f.isDirectory()){
File f1=new File("./testfile/chapter");
f1.mkdir();
System.out.println(f.getAbsolutePath());
String[] content=f.list();
for(String item:content){
System.out.println(item);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
File f=new File("./testfile");
BufferedWriter bw=new BufferedWriter(new FileWriter(f));//文件套在文件的传输方向套在缓冲区
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
//客户端
public class DailyAdviceClient {
public DailyAdviceClient(){
}
public void go(){
BufferedReader reader=null;
Socket s=null;
String str=null;
try{
s=new Socket("127.0.0.1",4242);
// InputStreamReader streamReader=new InputStreamReader(s.getInputStream();
InputStreamReader is=new InputStreamReader(s.getInputStream());
// FileReader fd=new FileReader(new File("./testfile/test.txt"));
reader=new BufferedReader(is);
// MyBase.MyPrint(s.isConnected());
while((str=reader.readLine())!=null){
System.out.println(str);
}
}catch(IOException ex){
ex.printStackTrace();
}finally{
MyIoTool.myClose(reader);
}
}
public static void main(String[] args){
System.out.println("客户开始");
DailyAdviceClient dac=new DailyAdviceClient();
dac.go();
}
}
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
//服务器
public class DailyAdviceServer {
String[] adviceList={"111111","2222222","3333333333","4444444444","55555555555","6666666666","7777777",
"888888888","99999999999999","1000000000000"};
public void go(){
PrintWriter pWriter=null;
String info=null;
ServerSocket serverSocket=null;
try{
serverSocket=new ServerSocket(4242);
while(true){
Socket socket=serverSocket.accept();
pWriter=new PrintWriter(socket.getOutputStream());
info=getAdvice();
System.out.println(info);
pWriter.println(info);
pWriter.close();//这儿不能把socket关闭了,否则传输失败.
//第二种方式
// BufferedWriter bos=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
// bos.write(getAdvice());
// bos.flush();
// bos.close();
}
}catch(IOException ex){
ex.printStackTrace();
}finally{
}
}
public String getAdvice(){
String advice=adviceList[(int)(Math.random()*adviceList.length)];
return advice;
}
public static void main(String[] args){
DailyAdviceServer dServer=new DailyAdviceServer();
System.out.println("开始");
dServer.go();
}
}
public class Myrunnable implements Runnable {
private int i=0;//可以共用对象的资源
public void run(){
i++;
go();
}
public void go(){
i++;
goMore();
}
public void goMore(){
MyBase.MyPrint("i am "+i+" "+Thread.currentThread().getName());
}
public static void main(String[] args){
Myrunnable myR=new Myrunnable();
Thread th=new Thread(myR);
Thread th1=new Thread(myR);
th.start();
th1.start();
MyBase.MyPrint("我是"+Thread.currentThread().getName());
}
}
package test;
//账户
public class BankAcount {
private int balance=100;
public int getBance(){
return balance;
}
public void withdrow(int amount){
balance=balance-amount;
}
}
package test;
//操作
public class RyAndMoJob implements Runnable {
BankAcount ba=new BankAcount();
public void run(){
for(int i=0;i<10;i++){
makeWrithdrow(7);
if(ba.getBance()<0){
System.out.println("Overdraw");
}
}
}
private void makeWrithdrow(int acount){
if(ba.getBance()>acount){
System.out.println(Thread.currentThread().getName()+"钱够");
try{
System.out.println(Thread.currentThread().getName()+"开始睡觉");
Thread.sleep(1000);
}catch(InterruptedException iex){
iex.printStackTrace();
}
System.out.println("取出");
ba.withdrow(acount);
System.out.println(Thread.currentThread().getName()+"取出成功");
System.out.println("还有"+ba.getBance());
}else{
System.out.println("sorry your money is not enough for"+Thread.currentThread().getName());
}
}
public static void main(String[] args){
RyAndMoJob ryAndMoJob=new RyAndMoJob();
Thread t1=new Thread(ryAndMoJob);
Thread t2=new Thread(ryAndMoJob);
t1.setName("Ry");
t2.setName("Mo");
t1.start();
t2.start();
}
}
//还有-5
//Overdraw
//sorry your money is not enough forRy
//Overdraw
//sorry your money is not enough forRy
//Overdraw
package syn;
public class TestSyn implements Runnable{
private int count;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<10;i++){
increase();
System.out.println(Thread.currentThread().getName()+"的数字是"+count);
}
}
//方法加入synchronized就可以解决更新丢失
public void increase(){
int i=count;
if(Thread.currentThread().getName().equals("One")){
try{
Thread.sleep(1000);
}catch(InterruptedException iex){
iex.printStackTrace();
}
}
if(Thread.currentThread().getName().equals("Two")){
try{
Thread.sleep(3000);
}catch(InterruptedException iex){
iex.printStackTrace();
}
}
count=i+1;
}
}
package syn;
public class TestSynTest{
public static void main(String[] args){
TestSyn ts=new TestSyn();
Thread t1=new Thread(ts);
Thread t2=new Thread(ts);
t1.setName("One");
t2.setName("Two");
t1.start();
t2.start();
}
}
//结果
// One的数字是1
// One的数字是2
// Two的数字是1
// One的数字是3
// One的数字是4
// One的数字是5
// Two的数字是2
// One的数字是6
// One的数字是7
// One的数字是8
// Two的数字是3
// One的数字是9
// One的数字是10
// Two的数字是4
// Two的数字是5
// Two的数字是6
// Two的数字是7
// Two的数字是8
// Two的数字是9
// Two的数字是10
package sisuo;
public class SiSuoTest {
public static String lock="lock1";
public static String lock2="lock2";
public static void main(String[] args){
Lock lk=new Lock();
Thread t1=new Thread(lk);
Thread t2=new Thread(lk);
t1.setName("Demo1");
t2.setName("Demo2");
t1.start();
t2.start();
}
}
class Lock implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
String name=Thread.currentThread().getName();
if(name=="Demo1"){
synchronized(SiSuoTest.lock){
System.out.println("进入"+name+"的lock1");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(SiSuoTest.lock2){
System.out.println("进入"+name+"的lock2");
}
}
}else if(name=="Demo2"){
synchronized(SiSuoTest.lock2){
System.out.println("进入"+name+"的lock1");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(SiSuoTest.lock){
System.out.println("进入"+name+"的lock2");
}
}
}
}
}
简单的聊天服务器代码(接收消息,转发给别人)综合socket和Thread
package Project1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
public class VerySimpleChatServer {
//保存用户
ArrayList clientOutputStreams;
public static void main(String[] args){
}
//将收到的消息发送给所有客户端
public void tellEveryone(String message){
Iterator it = clientOutputStreams.iterator();
PrintWriter writer=null;
while(it.hasNext()){
try{
writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public void go(){
clientOutputStreams = new ArrayList();
try{
//4343端口
ServerSocket serverSocket=new ServerSocket(4343);
while(true){
Socket clientSocket = serverSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t=new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("go a connection");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
//每一个用户就一个线程
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket socket;
public ClientHandler(Socket clientSocket){
try{
socket = clientSocket;
InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(isReader);
}catch(Exception ex){
ex.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
String message;
try{
//显示在控制台并告诉所有客户
while((message = reader.readLine())!=null){
System.out.println("read " + message);
tellEveryone(message);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
socket.shutdownInput();
socket.shutdownOutput();
TreeSet: 有序防重复
HashMap: 成对的name/value来保存与取出
LinkedList: 插入或删除中间元素所设计的高效率集合
HashSet: 防止重复的集合,能快速寻找相符的元素
LinkedHashMap: 类似HashMap,但可以记住元素插入的顺序,也可以设定成依照元素上次存取的先后来排序。
ArrayList: 插入对象直接排在最后面。
List<String> list = new ArrayList<>();
Collections.sort(list)
//第一种(一参数)
public static <T extends Comparable<? super T>> void sort(List<T> list) {
list.sort(null);
}
//第二种(二参数)
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
第一种
传入的类必须是Comparable,所以要实现Comparable
实现Comparable
//实现了Comparable
public class SongList implements Comparable{
private String title;
private String artist;
private String price;
public SongList(){
}
public SongList(String title,String artist,String price){
this.artist=artist;
this.price=price;
this.title=title;
}
public String getTitle(){
return title;
}
public String getArtist(){
return artist;
}
public String getPrice(){
return price;
}
//重写排序规则,与返回值得正负有关
@Override
public int compareTo(Object o) {
return -title.compareTo(((SongList)o).getTitle());
// TODO Auto-generated method stub
}
}
第二种
创建一个类再重新写方法
class ArtistCompare implements Comparator<SongList>{
//重写规则,与返回的规则有关。
@Override
public int compare(SongList o1, SongList o2) {
// TODO Auto-generated method stub
return -o1.getArtist().compareTo(o2.getArtist());
}
}
HashSet是Set接口的典型实现,大多数时候使用Set集合时就是使用这个实现类。HashSet按Hash算法来存储集合中的元素,因此具有很好的存取和查找性能,可以很好的去重,但是不会安顺序排。底层数据结构是哈希表。
HashSet还有一个子类LinkedList、使用链表维护元素的次序,这样使得元素看起来是以插入的顺序保存的,遍历集合LinkedHashSet集合里的元素时,集合将会按元素的添加顺序来访问集合里的元素,而且因为是链表所以插入和删除效率比较高。
LinkedHashSet依然是Set,因此它不允许集合重复。
TreeSet可以确保集合元素处于排序状态.
TreeSet内部实现的是红黑树,默认整形排序为从小到大
java源文件和编译的class文件要分开,好管理
所以就要创建source 和 classes文件
(在source目录下的命令)自动生成classes下的包目录
javac -d classes目录 java源文件目录
javac -d 命令如果要自动生成包的目录那么就必须在源文件中添加package的路径才行
执行程序命令
java 主类名字 (先要编译成class文件才可以运行)
jar -cvmf manifest.txt app.jar com 后面必须加com因为要指定从com目录开始找才行
manifest.txt内容:
Main-Class: com.wj.MyApp
manifest.txt 如果实在*.class之中那么就不用加com 里面的值只要是main类的命就行
jar -tf app.jar 列出文件列表
jar -xf app.jar解压成META-INF文件目录
执行jar包命令
java -jar jar包名
直接打包成jar,执行
这个需要安装java和helper app。
客户端点击JWS的应用程序链接(.Jnlp文件),下载jar文件,然后就可以运行了。
.jnlp:描述应用程序课执行jar文件的XML文件
RMI(远程方法调用)
需要服务器,客户端,服务器辅助设施,客户端辅助设施
需要客户端 访问 客户端辅助设施 访问服务器辅助设施 访问服务器
关键包:rmi
关键类:Remote、UnicastRemoteObject
关键:stub和skeleton,rmiregistry
Servlet可以配合Jini(用来查询服务器的服务的)