IO-必须掌握的技术

IO一直是软件开发中的核心部分之一,伴随着海量数据增长和分布式系统的发展,IO扩展能力越发重要。首先IO不仅指文件IO,还有网络IO。

文件IO有很多种,基于不同的IO抽象模型和交互方式,可以区分为JAVA IO,NIO,NIO2(AIO)。

首先,传统的 java.io 包,它基于流模型实现,提供了我们最熟知的一些 IO 功能,比如 File 抽象、输入输出流等。交互方式是同步、阻塞的方式,也就是说,在读取输入流或者写入输出流时,在读、写动作完成之前,线程会一直阻塞在那里,它们之间的调用是可靠的线性顺序。

java.io 包的好处是代码比较简单、直观,缺点则是 IO 效率和扩展性存在局限性,容易成为应用性能的瓶颈。

很多时候,人们也把 java.net 下面提供的部分网络 API,比如 Socket、ServerSocket、HttpURLConnection 也归类到同步阻塞 IO 类库,因为网络通信同样是 IO 行为

在java程序中,数据的输入和输出是以流的方式进行的。java.io定义了很多的流类型来实现输入/输出的功能。具体的看下面的图。

接下来放2个IO例子

文件IO

package io;
import java.io.*;
public class TestFileWriter {
  public static void main(String[] args) {
    FileWriter fw = null;
    File file = new File(".");
    String path = file.getAbsoluteFile().getParent() + 
    		             "\\data\\unicode.dat";
    try {
      fw = new FileWriter(path);
      for(int c=0;c<=50000;c++){
        fw.write(c);
      }
      fw.close();
    } catch (IOException e1) {
    	e1.printStackTrace();
      System.out.println("文件写入错误");
      System.exit(-1);
    }
    System.out.println("文件写入成功");
  }
}

网络IO

client

package socket;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient extends Frame
{
	TextArea ta = new TextArea();
	TextField tf = new TextField();
	public void launchFrame() throws Exception
	{
		this.add(ta, BorderLayout.CENTER);
		this.add(tf, BorderLayout.SOUTH);
		tf.addActionListener(
			new ActionListener() 
			{
				public void actionPerformed(ActionEvent ae)
				{
					try {
						String sSend = tf.getText();
						if(sSend.trim().length() == 0) return;
						ChatClient.this.send(sSend);
						tf.setText("");
						ta.append(sSend + "\n");
					}
					catch (Exception e) { e.printStackTrace(); }
				}
			}
			);
		
		this.addWindowListener(
			new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					System.exit(0);
				}
			}
			);
		setBounds(300,300,300,400);
		setVisible(true);
		tf.requestFocus();
	}
	
	Socket s = null;
	
	public ChatClient() throws Exception
	{
		s = new Socket("127.0.0.1", 8888);
		launchFrame();
		(new Thread(new ReceiveThread())).start();
	}
	
	public void send(String str) throws Exception
	{
		DataOutputStream dos = new DataOutputStream(s.getOutputStream());
		dos.writeUTF(str);
	}
	
	public void disconnect() throws Exception
	{
		s.close();
	}
	
	public static void main(String[] args) throws Exception
	{
		BufferedReader br = new BufferedReader (
								new InputStreamReader(System.in));
		ChatClient cc = new ChatClient();
		String str = br.readLine();
		
		while(str != null && str.length() != 0)
		{
			cc.ta.append(str + "\n");
			cc.send(str);
			str = br.readLine();
		}
		cc.disconnect();
	}
	
	class ReceiveThread implements Runnable
	{
		public void run()
		{
			if(s == null) return;
			try {
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String str = dis.readUTF();
				while (str != null && str.length() != 0)
				{
					//System.out.println(str);
					ChatClient.this.ta.append(str + "\n");
					str = dis.readUTF();
				}
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
		}
	}
}

server

package socket;
import java.net.*;
import java.util.*;

import socket.ChatServer.ClientConn;

import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class ChatServer extends Frame
{
	TextArea ta = new TextArea();
	public void launchFrame()
	{
		add(ta, BorderLayout.CENTER);
		setBounds(0,0,200,300);	
		this.addWindowListener(
			new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					System.exit(0);
				}
			}
			);
		setVisible(true);
	}
	
	ServerSocket server = null;
	Collection cClient = new ArrayList();
	
	public ChatServer(int port) throws Exception
	{
		server = new ServerSocket(port);
		launchFrame();
	}
	
	public void startServer() throws Exception
	{
		while(true)
		{
			Socket s = server.accept();
			cClient.add( new ClientConn(s) );
			ta.append("NEW-CLIENT " + s.getInetAddress() + ":" + s.getPort());
			ta.append("\n" + "CLIENTS-COUNT: " + cClient.size() + "\n\n");
		}
	}
	
	class ClientConn implements Runnable
	{
		Socket s = null;
		public ClientConn(Socket s)
		{
			this.s = s;
			(new Thread(this)).start();
		}
		
		public void send(String str) throws IOException
		{
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			dos.writeUTF(str);
		}
		
		public void dispose()
		{
			try {
				if (s != null) s.close();
				cClient.remove(this);
				ta.append("A client out! \n");
				ta.append("CLIENT-COUNT: " + cClient.size() + "\n\n");
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		
		public void run()
		{
			try {
				
				DataInputStream dis = new DataInputStream(s.getInputStream());
				String str = dis.readUTF();
				
				while(str != null && str.length() !=0)
				{
					System.out.println(str);
					ta.append(str + "\n");
					for(Iterator it = cClient.iterator(); it.hasNext(); )
					{
						ClientConn cc = (ClientConn)it.next();
						if(this != cc)
						{
							cc.send(str);
						}
					}
					str = dis.readUTF();
					//send(str);
				}
				this.dispose();
			} 
			catch (Exception e) 
			{
				System.out.println("client quit");
				this.dispose();
			}
			
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		ChatServer cs = new ChatServer(8888);
		cs.startServer();
	}
}

当然上面的都是最基础的了,如果想使用好IO,那么Netty必须要研究一下的了。

你可能感兴趣的:(java学习)