java-每天一练2_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java-每天一练2

java-每天一练2

 2014/4/16 18:28:44  lixiao_lin  程序员俱乐部  我要评论(0)
  • 摘要:一、packagecom.nmg.service.test;importjava.util.*;importjava.io.*;/***<p>Title:标准输入输出</p>*<p>Description:接收标准的键盘输入和输出到屏幕。</p>*<p>Copyright:Copyright(c)2014</p>*<p>Filename:StandardIO.java</p>
  • 标签:Java
一、
class="java">
package com.nmg.service.test;

import java.util.*;
import java.io.*;

/**
 * <p>Title: 标准输入输出</p>
 * <p>Description: 接收标准的键盘输入和输出到屏幕。</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: StandardIO.java </p>
 * @author llx
 * @version 1.0
 *
 */
public class StandardIO {
/**
 * <br>方法说明:主方法
 * <br>输入参数:
 * <br>返回类型:
 */
	public static void main(String[] args){
		Vector vTemp = new Vector();
		boolean flag = true;
		while(flag){
			System.out.println("input>");
			String sTemp = "";
			//读取输入,System.in表示接收键盘输入流
			BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
			try {
				//读取一行输入
				sTemp = stdin.readLine();
				//System.out.println("sTemp---------" + sTemp);
			} catch (IOException e) {
				System.err.print("IO error!");
			}
			//解析输入命令
			String sCMD = "";
			String sContext = "";
			int point = sTemp.indexOf(":");
			//System.out.println("point-----: " + point);//indexOf()返回某个指定的字符串值(":")在字符串中首次出现的位置,从0开始,没有则返回-1,方便判断和截取字符串
			if(point == -1){
				sCMD = sTemp.trim();//trim()去掉字符序列左边和右边的空格
				//System.out.println("sCMD-----:" + sCMD);
			}else{
				sCMD = sTemp.substring(0, point);//substring()截取字符串,从0个位置到point位置的字符串
				//System.out.println("sCMD----" + sCMD);
				sContext = sTemp.substring(point + 1); //返回一个新的字符串,从point+1开始,直到末尾
				//System.out.println("sContext----" + sContext);;
			}
			//添加数据
			if (sCMD.equalsIgnoreCase("in")) {
				if (sContext.equals("")) {
					System.err.print("this command format is errer!");
				}else {
					vTemp.addElement(sContext);
				}
			}
			//查看结果
			else if (sCMD.equalsIgnoreCase("out")) {
				for(int i = 0; i < vTemp.size(); i++){
					System.out.println(i + ":" + vTemp.elementAt(i));
				}
			}
			//结束
			else if (sCMD.equals("quit")) {
				flag = false;
			}
			else {
				System.err.print("this command don't run !");
				System.out.println("use: in:command");
				System.out.println("use: out");
			}
		}
	}
}



二、
package com.nmg.service.test;

import java.io.*;
/**
 * <p>Title: 读取和写入文件</p>
 * <p>Description: 使用字节流方式操作文件,读取和写入文件。</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: CopyBytes.java</p>
 * @author llx
 * @version 1.0
 */
public class CopyBytes {
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
    public static void main(String[] args) throws IOException {
        String sFile;
        String oFile;
        if(args.length<2){
          System.out.println("USE:java CopyBytes source file | object file");
          return;
        }else{
          sFile = args[0];
          oFile = args[1];
        }
        try{
          File inputFile = new File(sFile);//定义读取源文件
          File outputFile = new File(oFile);//定义拷贝目标文件
          //定义输入文件流
          FileInputStream in = new FileInputStream(inputFile);
          //将文件输入流构造到缓存
          BufferedInputStream bin = new BufferedInputStream(in);
          //定义输出文件流
          FileOutputStream out = new FileOutputStream(outputFile);
          //将输出文件流构造到缓存
          BufferedOutputStream bout = new BufferedOutputStream(out);
          int c;
          //循环读取文件和写入文件
          while ((c = bin.read()) != -1)
             bout.write(c);
          //关闭输入输出流,释放资源
          bin.close();
          bout.close();
        }catch(IOException e){
          //文件操作,捕获IO异常。
          System.err.println(e);
        }
    }
}



三、
import java.io.*;

/**
 * <p>Title: 文件的读取和写入(字符)</p>
 * <p>Description: 使用FileReader和FileWriter类,采用字符文件访问方式操作文件。</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: </p>
 * @author llx
 * @version 1.0
 */
public class CopyChar {
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
    public static void main(String[] args) throws IOException {
        String sFile;
        String oFile;
        if(args.length<2){
          System.out.println("USE:java CopyChar source file | object file");
          return;
        }else{
          sFile = args[0];
          oFile = args[1];
        }
        try{
          File inputFile   = new File(sFile);//定义读取的文件源
          File outputFile = new File(oFile);//定义拷贝的目标文件
          //定义输入文件流
          FileReader in   = new FileReader(inputFile);
          //将文件输入流构造到缓存
          BufferedReader bin = new BufferedReader(in);
          //定义输出文件流
          FileWriter out  = new FileWriter(outputFile);
          //将输出文件流构造到缓存
          BufferedWriter bout = new BufferedWriter(out);
          int c;
          //循环读取和输入文件。
          while ((c = bin.read()) != -1)
             bout.write(c);
          bin.close();
          bout.close();
        }catch(IOException e){
          //文件操作,捕获IO异常。
          System.err.println(e);
        }
    }
}



四、
package com.nmg.service.test;

import java.io.*;
import java.util.*;
/**
 * <p>Title: 文件操作</p>
 * <p>Description: 演示文件的删除和获取文件的信息</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: </p>
 * @author llx
 * @version 1.0
 */
public class FileOperation{
/**
 *<br>方法说明:删除文件
 *<br>输入参数:String fileName 要删除的文件名
 *<br>返回类型:boolean 成功为true
 */
  public boolean delFile(String fileName){
  	try{
  	  //删除文件
      boolean success = (new File(fileName)).delete();
      if (!success) {
         System.out.println("delete file error!");
         return false;
      }else{
         return true;
      }
    }catch(Exception e){
      System.out.println(e);
      return false;
    }
  }
/**
 *<br>方法说明:获取文件信息
 *<br>输入参数:String Name 文件名
 *<br>返回类型:String[] 文件信息数组
 */
  public String[] getFileInfo(String Name){
    try{
      File file = new File(Name);
      //获取文件修改日期(返回的是句)
      long modifiedTime = file.lastModified();
      //获取文件长度(单位:Bite)
      long filesize = file.length();
      //测试文件是否可读
      boolean cr = file.canRead();
      //测试文件是否可写
      boolean cw = file.canWrite();
      //测试文件是否隐藏
      boolean ih = file.isHidden();
      
      String[] sTemp = new String[6];
      sTemp[0] = String.valueOf(filesize);
      sTemp[1] = getDateString(modifiedTime);
      sTemp[2] = String.valueOf(cr);
      sTemp[3] = String.valueOf(cw);
      sTemp[4] = String.valueOf(ih);
      sTemp[5] = String.valueOf(file.getCanonicalPath());
      return sTemp;
    }catch(Exception e){
      System.out.println(e);
      return null;
    }
  }

/**
 *<br>方法说明:将毫秒数字转换为日期
 *<br>输入参数:mill    毫秒数
 *<br>返回类型:String 字符 格式为:yyyy-mm-dd hh:mm
 */
  public static String getDateString(long mill)
  {
    if(mill < 0) return  "";
    
    Date date = new Date(mill);
    Calendar rightNow = Calendar.getInstance();
    rightNow.setTime(date);
    int year = rightNow.get(Calendar.YEAR);
    int month = rightNow.get(Calendar.MONTH);
    int day = rightNow.get(Calendar.DAY_OF_MONTH);
    int hour = rightNow.get(Calendar.HOUR_OF_DAY);
    int min = rightNow.get(Calendar.MINUTE);

    return year + "-" + (month <10 ? "0" + month : "" + month) + "-" 
           +  (day <10 ? "0" + day : "" + day)
           +  (hour <10 ? "0" + hour : "" + hour)+":"
           + (min <10 ? "0" + min : "" + min);
  }
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
  public static void main(String[] args){
  	try{
      FileOperation fo = new FileOperation();
      if(args.length==0){
        return;
      }else{
        String cmd = args[0];
        if(cmd.equals("del")){
          boolean bdel = fo.delFile(args[1]);
          System.out.println(bdel);
        }else if(cmd.equals("info")){
          String[] sTemp = fo.getFileInfo(args[1]);
          for(int i=0;i<sTemp.length;i++)
            System.out.println(sTemp[i]);
        }
      
      }
    }catch(Exception e){
      return;
    }
  }
}


五、
/**
 * <p>Title: 目录操作</p>
 * <p>Description: 演示列目录下的文件,和移动一个目录</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: Dir.java</p>
 * @author llx
 * @version 1.0
 */
import java.io.*;
public class Dir{
 /**
 *<br>方法说明:实现目录列表
 *<br>输入参数:
 *<br>返回类型:
 */ 
  public String[] DirList(String pathName){
    try{
      File path = null;
      String[] fileList;
      //如果没有指定目录,则列出当前目录。
      if(pathName.equals(""))
        path = new File(".");
      else
        path = new File(pathName);
      //获取目录文件列表
      if(path.isDirectory())
        fileList = path.list();
      else
        return null;
     return fileList;
    }catch(Exception e){
      System.err.println(e);
      return null;
    }
  }
/**
 *<br>方法说明:移动一个目录
 *<br>输入参数:String sou 源目录, String obj 新目录
 *<br>返回类型:
 */
  public boolean DirMove(String sou, String obj){
    try{
     //检查源文件是否存在
      boolean sexists = (new File(sou)).isDirectory();
      if(!sexists) return false;
      boolean oexists = (new File(obj)).isDirectory();
      //目标目录不存在,建立一个
      if(!oexists){
        (new File(obj)).mkdirs();
      }
   
        File file = new File(sou);
        File dir = new File(obj);
        //移动目录
        boolean success = file.renameTo(new File(dir, file.getName()));
        if (!success) {
         System.out.println("copy error!");
         return false;
        }
        else return true;
    }catch(Exception e){
    	System.out.println(e);
    	return false;
    }
    
  }

/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
  public static void main(String[] args){
     Dir d = new Dir();
    if(args.length==0){
      return;
    }else{
      String cmd = args[0];
      if(cmd.equals("list")){
      	if(args.length!=2) return;
        String[] sTemp = d.DirList(args[1]);
        for(int i=0;i<sTemp.length;i++)
          System.out.println(sTemp[i]);
      }else if(cmd.equals("move")){
      	if(args.length!=3) return;      	
        d.DirMove(args[1],args[2]);
      }
      
    }
   }
} 



六、
import java.io.*;
/**
 * <p>Title: 读取随机文件</p>
 * <p>Description: 演示使用RandomAccessFile类读取文件。</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: RandFile.java</p>
 * @author llx
 * @version 1.0
 */
public class RandFile{
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
  public static void main(String[] args){
    String sFile;
    if(args.length<1){
      System.out.println("USE:java RandFile fileName");
      return;
    }else{
      sFile = args[0];
    }
    //接受IOException异常
    try{
      //构造随机访问文件,使用可读写方式。
      RandomAccessFile rf = new  RandomAccessFile(sFile, "rw");
      for(int i = 0; i < 10; i++)
      	rf.writeDouble(i*1.414);
      rf.close();
      //构造一个随机访问文件,使用只读方式
      rf = new RandomAccessFile(sFile, "rw");
      rf.seek(5*8);
      rf.writeDouble(47.0001);
      rf.close();
      //构造一个随机文件访问文件,使用只读方式。
      rf = new RandomAccessFile(sFile, "r");
      for(int i = 0; i < 10; i++)
       	System.out.println("Value " + i + ": " + rf.readDouble());
      rf.close();
     }catch(IOException e){
       System.out.println(e);
     }
  }
}



七、
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import java.io.*;
import java.util.*;
import java.awt.Color;

/**
 * <p>Title: 生成PDF文件</p>
 * <p>Description: 本实例通过使用iText包生成一个表格的PDF文件</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: MyPDF.java</p>
 * @author llx
 * @version 1.0
 */
public class MyPDF{
/**
 *<br>方法说明:写PDF文件
 *<br>输入参数:
 *<br>返回类型:
 */
  public void write(){
   try{
     Document document=new Document(PageSize.A4, 50, 50, 100, 50);
     Rectangle pageRect=document.getPageSize();
     PdfWriter.getInstance(document, new FileOutputStream("tables.pdf"));
     //创建汉字字体
     BaseFont bfSong = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
     Font fontSong = new Font(bfSong, 10, Font.NORMAL);
     // 增加一个水印
     try {
         Watermark watermark = new Watermark(Image.getInstance("test.jpg"), pageRect.left()+50,pageRect.top()-85);
         watermark.scalePercent(50);
         document.add(watermark);
     }catch(Exception e) {
		  System.err.println("请查看文件“test.jpg”是否在正确的位置?");
     }
     
      // 为页增加页头信息
     HeaderFooter header = new HeaderFooter(new Phrase("Java实例一百例",fontSong), false);
     header.setBorder(2);
     header.setAlignment(Element.ALIGN_RIGHT);
     document.setHeader(header);
     
	  // 为页增加页脚信息
     HeaderFooter footer = new HeaderFooter(new Phrase("第 ",fontSong),new Phrase(" 页",fontSong));
     footer.setAlignment(Element.ALIGN_CENTER);
     footer.setBorder(1);
     document.setFooter(footer);

      // 打开文档
     document.open(); 
     //构造表格
     Table table = new Table(4);
     table.setDefaultVerticalAlignment(Element.ALIGN_MIDDLE);
     table.setBorder(Rectangle.NO_BORDER);
     int hws[] = {10, 20, 10, 20,};
     table.setWidths(hws);
     table.setWidth(100);
     //表头信息
     Cell cellmain = new Cell(new Phrase("用户信息",new Font(bfSong, 10, Font.BOLD,new Color(0,0,255))));
     cellmain.setHorizontalAlignment(Element.ALIGN_CENTER);
     cellmain.setColspan(4);
     cellmain.setBorder(Rectangle.NO_BORDER);
     cellmain.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
     table.addCell(cellmain);
      //分表头信息
     Cell cellleft= new Cell(new Phrase("收货人信息",new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));
     cellleft.setColspan(2);
     cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);
     table.addCell(cellleft);
     Cell cellright= new Cell(new Phrase("订货人信息",new Font(bfSong, 10, Font.ITALIC,new Color(0,0,255))));
     cellright.setColspan(2);
     cellright.setHorizontalAlignment(Element.ALIGN_CENTER);
     table.addCell(cellright);
     
     //收货和订货人信息,表体内容
     table.addCell(new Phrase("姓名",fontSong));
     table.addCell(new Phrase("张三",fontSong));
     table.addCell(new Phrase("姓名",fontSong));
     table.addCell(new Phrase("李四",fontSong));

     table.addCell(new Phrase("电话",fontSong));
     table.addCell(new Phrase("23456789",fontSong));
     table.addCell(new Phrase("电话",fontSong));
     table.addCell(new Phrase("9876543",fontSong));

     table.addCell(new Phrase("邮编",fontSong));
     table.addCell(new Phrase("100002",fontSong));
     table.addCell(new Phrase("邮编",fontSong));
     table.addCell(new Phrase("200001",fontSong));

     table.addCell(new Phrase("地址",fontSong));
     table.addCell(new Phrase("北京西城区XX路XX号",fontSong));
     table.addCell(new Phrase("地址",fontSong));
     table.addCell(new Phrase("上海陆家嘴区XX路XX号",fontSong));

     table.addCell(new Phrase("电子邮件",fontSong));
     table.addCell(new Phrase("zh_san@hotmail.com",fontSong));
     table.addCell(new Phrase("电子邮件",fontSong));
     table.addCell(new Phrase("li_si@hotmail.com",fontSong));
     //将表格添加到文本中
     document.add(table);
     //关闭文本,释放资源
     document.close(); 
     
   }catch(Exception e){
     System.out.println(e);   
   }
  }
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
  public static void main(String[] arg){
    MyPDF p = new MyPDF();
    p.write();
  }
}


八、
//文件名:MyZip.java
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
 * <p>Title: 文件压缩和解压</p>
 * <p>Description: 使用ZipInputStream和ZipOutputStream对文件
 *                 和目录进行压缩和解压处理</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: MyZip.java</p>
 * @author llx
 * @version 1.0
 */
public class MyZip{
/**
 *<br>方法说明:实现文件的压缩处理
 *<br>输入参数:String[] fs 压缩的文件数组
 *<br>返回类型:
 */
  public void ZipFiles(String[] fs){
   try{
     String fileName = fs[0];
     FileOutputStream f =
       new FileOutputStream(fileName+".zip");
     //使用输出流检查
     CheckedOutputStream cs = 
        new CheckedOutputStream(f,new Adler32());
      //声明输出zip流
      ZipOutputStream out =
        new ZipOutputStream(new BufferedOutputStream(cs));
      //写一个注释
      out.setComment("A test of Java Zipping");
      //对多文件进行压缩
      for(int i=1;i<fs.length;i++){
        System.out.println("Write file "+fs[i]);
        BufferedReader in =
           new BufferedReader(
             new FileReader(fs[i]));
         out.putNextEntry(new ZipEntry(fs[i]));
         int c;
         while((c=in.read())!=-1)
          out.write(c);
        in.close();
       }
       //关闭输出流
       out.close();
       System.out.println("Checksum::"+cs.getChecksum().getValue());
    }catch(Exception e){
       System.err.println(e);
    }
  }

/**
 *<br>方法说明:解压缩Zip文件
 *<br>输入参数:String fileName 解压zip文件名
 *<br>返回类型:
 */
  public void unZipFile(String fileName){
    try{
       System.out.println("读取ZIP文件........");
       //文件输入流
       FileInputStream fi =
         new FileInputStream(fileName+".zip");
       //输入流检查
       CheckedInputStream csi = new CheckedInputStream(fi,new Adler32());
       //输入流压缩
       ZipInputStream in2 =
         new ZipInputStream(
           new BufferedInputStream(csi));
       ZipEntry ze;
       System.out.println("Checksum::"+csi.getChecksum().getValue());
       //解压全部文件
       while((ze = in2.getNextEntry())!=null){
         System.out.println("Reading file "+ze);
         int x;
         while((x= in2.read())!=-1)
           //这里是写文件,write是以byte方式输出。
           System.out.write(x);
       }
       in2.close();
    }catch(Exception e){
      System.err.println(e);
    }
  }
/**
 *<br>方法说明:读取Zip文件列表
 *<br>输入参数:String fileName zip文件名
 *<br>返回类型:Vector 文件列表
 */
  public Vector listFile(String fileName){
    try{
       String[] aRst=null;
       Vector vTemp = new Vector();
       //zip文件对象
       ZipFile zf = new ZipFile(fileName+".zip");
       Enumeration e = zf.entries();
       while(e.hasMoreElements()){
         ZipEntry ze2 = (ZipEntry)e.nextElement();
         System.out.println("File: "+ze2);
         vTemp.addElement(ze2);
       }
       return  vTemp;
    }catch(Exception e){
      System.err.println(e);
      return null;
    }
  }
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
  public static void main(String[] args){
    try{
     String fileName = args[0];
     MyZip myZip = new MyZip();
     myZip.ZipFiles(args);
     myZip.unZipFile(fileName);
     Vector dd = myZip.listFile(fileName);
     System.out.println("File List: "+dd);
    }catch(Exception e){
    	e.printStackTrace();
    }
  }
}



九、
import java.io.*;
/**
 * <p>Title: 运行系统命令</p>
 * <p>Description:运行一个系统的命令,演示使用Runtime类。</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: CmdExec.java</p>
 * @author llx
 * @version 1.0
 */
public class CmdExec {
/**
 *<br>方法说明:构造器,运行系统命令
 *<br>输入参数:String cmdline 命令字符
 *<br>返回类型:
 */
  public CmdExec(String cmdline) {
    try {
     String line;
     //运行系统命令
     Process p = Runtime.getRuntime().exec(cmdline);
     //使用缓存输入流获取屏幕输出。
     BufferedReader input = 
       new BufferedReader
         (new InputStreamReader(p.getInputStream()));
     //读取屏幕输出
     while ((line = input.readLine()) != null) {
       System.out.println("java print:"+line);
       }
     //关闭输入流
     input.close();
     } 
    catch (Exception err) {
     err.printStackTrace();
     }
   }
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
public static void main(String argv[]) {
   new CmdExec("myprog.bat");
  }
}




十、
import java.net.*;
/**
 * <p>Title: 获取本机名称和IP地址</p>
 * <p>Description: 使用InetAddress来获取本机名称和IP地址信息</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: NetInfo.java</p>
 * @author llx
 * @version 1.0
 */
public class NetInfo {
/**
 *<br>方法说明:主方法
 *<br>输入参数:
 *<br>返回类型:
 */
 public static void main(String[] args) {
    new NetInfo().say();
    }
/**
 *<br>方法说明:查看本机名称和IP地址
 *<br>输入参数:
 *<br>返回类型:
 */
 public void say() {
   try {
   InetAddress i = InetAddress.getLocalHost();
   System.out.println(i);                  //计算机名称和IP
   System.out.println(i.getHostName());    //名称
   System.out.println(i.getHostAddress()); //只获得IP
   }
   catch(Exception e){e.printStackTrace();}
 }
}




十一、
import java.io.*;
import java.net.*; 
/**
 * <p>Title: 简单服务器客户端</p>
 * <p>Description: 本程序是一个简单的客户端,用来和服务器连接</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: SampleClient.java</p>
 * @author llx
 * @version 1.0
 */
public class SampleClient{
  public static void main(String[] arges){
    try{
      //获取一个IP。null表示本机
      InetAddress addr = InetAddress.getByName(null);
      //打开8888端口,与服务器建立连接
      Socket sk = new Socket (addr, 8888);
      //缓存输入
      BufferedReader in = new BufferedReader (
                         new InputStreamReader (sk.getInputStream ()));
      //缓存输出
      PrintWriter out = new PrintWriter (
                         new BufferedWriter(
                          new OutputStreamWriter(
                           sk.getOutputStream ())), true);
     //向服务器发送信息
     out.println ("你好!");
     //接收服务器信息
     System.out.println (in.readLine ());
    }catch(Exception e){
      System.out.println(e);
    }
  }
}

///////////

import java.net.*;
import java.io.*;
/**
 * <p>Title: 简单服务器服务端</p>
 * <p>Description: 这是一个简单的服务器端程序</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: SampleServer.java</p>
 * @author llx
 * @version 1.0
 */
public class SampleServer{
  public static void main(String[] arges){
    try{
      int port = 8888;
      //使用8888端口创建一个ServerSocket
      ServerSocket mySocket = new ServerSocket(port);
      //等待监听是否有客户端连接
      Socket sk = mySocket.accept();
      //输入缓存
      BufferedReader in = new BufferedReader (
                         new InputStreamReader (sk.getInputStream ()));
      //输出缓存
      PrintWriter out = new PrintWriter (
                         new BufferedWriter(
                          new OutputStreamWriter(
                           sk.getOutputStream ())), true);
      //打印接收到的客户端发送过来的信息
      System.out.println("客户端信息:"+in.readLine ());
      //向客户端回信息
      out.println("你好,我是服务器。我使用的端口号: "+port); 
    }catch(Exception e){
      System.out.println(e);
    }
  }
}




十三、
// 文件名:MoreServer.java
import java.io.*;
import java.net.*;
import java.util.*;
/**
 * <p>Title: 多线程服务器</p>
 * <p>Description: 本实例使用多线程实现多服务功能。</p>
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Filename: </p>
 * @author llx
 * @version 1.0
 */
class MoreServer
{
 public static void main (String [] args) throws IOException
 {
   System.out.println ("Server starting...\n"); 
   //使用8000端口提供服务
   ServerSocket server = new ServerSocket (8000);
   while (true)
   {
    //阻塞,直到有客户连接
     Socket sk = server.accept ();
     System.out.println ("Accepting Connection...\n");
     //启动服务线程
     new ServerThread (sk).start ();
   }
 }
}
//使用线程,为多个客户端服务
class ServerThread extends Thread
{
 private Socket sk;
 
 ServerThread (Socket sk)
 {
  this.sk = sk;
 }
//线程运行实体
 public void run ()
 {
  BufferedReader in = null;
  PrintWriter out = null;
  try{
    InputStreamReader isr;
    isr = new InputStreamReader (sk.getInputStream ());
    in = new BufferedReader (isr);
    out = new PrintWriter (
           new BufferedWriter(
            new OutputStreamWriter(
              sk.getOutputStream ())), true);

    while(true){
      //接收来自客户端的请求,根据不同的命令返回不同的信息。
      String cmd = in.readLine ();
      System.out.println(cmd);
      if (cmd == null)
          break;
      cmd = cmd.toUpperCase ();
      if (cmd.startsWith ("BYE")){
      	 out.println ("BYE");
         break;
      }else{
        out.println ("你好,我是服务器!");
      }
    }
    }catch (IOException e)
    {
       System.out.println (e.toString ());
    }
    finally
    {
      System.out.println ("Closing Connection...\n");
      //最后释放资源
      try{
       if (in != null)
         in.close ();
       if (out != null)
         out.close ();
        if (sk != null)
          sk.close ();
      }
      catch (IOException e)
      {
      	System.out.println("close err"+e);
      }
    }
 }
}

///////////


//文件名:SocketClient.java
import java.io.*;
import java.net.*; 
class SocketThreadClient extends Thread
{
 public static int count = 0;
//构造器,实现服务
 public SocketThreadClient (InetAddress addr)
 {
  count++;
  BufferedReader in = null;
  PrintWriter out = null;
  Socket sk = null;
  try{
  //使用8000端口
   sk = new Socket (addr, 8000);
   InputStreamReader isr;
   isr = new InputStreamReader (sk.getInputStream ());
   in = new BufferedReader (isr);
   //建立输出
   out = new PrintWriter (
          new BufferedWriter(
           new OutputStreamWriter(
             sk.getOutputStream ())), true);
   //向服务器发送请求
   System.out.println("count:"+count);
   out.println ("Hello");
   System.out.println (in.readLine ());
   out.println ("BYE");
   System.out.println (in.readLine ());

  }
  catch (IOException e)
  {
   System.out.println (e.toString ());
  }
  finally
  {
   out.println("END");
   //释放资源
   try
   {
    if (in != null)
     in.close ();
    if (out != null)
     out.close ();
    if (sk != null)
     sk.close ();
   }
   catch (IOException e)
   {
   }
  }
 }
}
//客户端
public class SocketClient{
  public static void main(String[] args) throws IOException,InterruptedException
  {
    InetAddress addr = InetAddress.getByName(null);
      for(int i=0;i<10;i++)
         new SocketThreadClient(addr);
      Thread.currentThread().sleep(1000);
  } 
}






  • 操作excel.zip (369.2 KB)
  • 下载次数: 0
  • 生成pdf文件.zip (334.2 KB)
  • 下载次数: 0
发表评论
用户名: 匿名