将网络上的HTML文件写入到本地一个文件里
1 public static void main(String[] args) throws Exception { 2 URL url=new URL("http://www.qtfy30.cn/"); 3 InputStream is = url.openStream(); 4 5 OutputStream os =new FileOutputStream("E:/test/tt1.html"); 6 7 byte[] b=new byte[1024]; 8 9 int length=0;10 //读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。 11 12 while(-1!=(length = is.read(b,0,b.length))){13 os.write(b, 0, length);14 }15 os.flush();16 os.close();17 is.close();18 }
实现客户端和服务器端的网络交互
文件列表:
1. 服务端 2. 客户端 3. 接收器线程1 //1.服务端 2 public class SocketService { 3 public static void main(String[] args) throws Exception { 4 5 //socket -网络通信一端的端口 ServerSocket 网络通信服务 6 7 ServerSocket ss= new ServerSocket(1000); 8 // 接收网络通信服务 9 Socket socket =ss.accept(); 10 11 12 //输入流 由通信端口输入 13 InputStream is =socket.getInputStream(); 14 // 输出流 由通信端口输出 15 OutputStream os =socket.getOutputStream(); 16 17 //new一个线程 传入 socket接收信息 18 new AcceptThread("aa", socket).start(); 19 20 //接收字节的数组 21 22 byte[] buffer = new byte[200]; 23 24 25 int length = 0; 26 //系统输入 27 Scanner sc = new Scanner(System.in); 28 29 String str = null; 30 31 //接收console输入的信息 并发送到client端(AcceptThread线程在运行,接收socket的信息) 32 while(true){ 33 if(sc.hasNext()){ 34 str = sc.nextLine(); 35 String messageString = new String (str.getBytes("GBK")).trim(); 36 os.write(messageString.getBytes()); 37 os.flush(); 38 } 39 } 40 41 42 } 43 } 44 //2.客户端 45 public class SocketClientA { 46 public static void main(String[] args) throws Exception { 47 48 Socket socket1 = new Socket("127.0.0.1",1000); 49 InputStream is = socket1.getInputStream(); 50 OutputStream os = socket1.getOutputStream(); 51 new AcceptThread("aa", socket1).start(); 52 53 54 byte[] buffer = new byte[200]; 55 int length = 0; 56 Scanner sc = new Scanner(System.in); 57 String str = null; 58 while(null!=(str=sc.next())){ 59 String messageString = new String (str.getBytes("utf-8")); 60 os.write(messageString.getBytes()); 61 os.flush(); 62 } 63 is.close(); 64 os.close(); 65 socket1.close(); 66 } 67 } 68 69 //3.接收信息线程 70 public class AcceptThread extends Thread{ 71 72 73 74 private Socket socket; 75 76 //构造函数 传入socket 77 public AcceptThread(String name ,Socket socket){ 78 super (name); 79 this.socket=socket; 80 } 81 82 83 //重载 run函数 84 85 @Override 86 public void run(){ 87 super.run(); 88 89 InputStream is=null; 90 91 byte[] b=new byte[200]; 92 93 int length = 0; 94 //接收socket 传来的信息 95 try{ 96 is=socket.getInputStream(); 97 while(-1 != (length=is.read(b, 0, b.length))){ 98 String str=new String (b,0,length); 99 System.out.println(str);100 }101 }catch (Exception e){102 e.printStackTrace();103 }104 105 }106 107 }