输入输出流的简单实际应用(序列化 文件读写 socket)

原本以为输入输出流都是一一对应的,所以用的时候也是一一对应的的。但是实际应用时发现并不是如此,mark一下。以下列举三点常用的地方,当然各种情况应该也可以换做其他输入输出流。

1.序列化

FileOutputStream + ObjectOutputStream//序列化
FileInputStream + ObjectInputStream//反序列化
调用方法write/read Object
以文件的形式保存对象或者从文件取出数据保存为对象,所以比较好记。

        List<Integer> removeCategoryIdList = new ArrayList<>(Arrays.asList(-109, -110, -111));
        //序列化
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("object.out");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(removeCategoryIdList);
            oos.flush();
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //反序列化
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("object.out");
            ObjectInputStream ois = new ObjectInputStream(fis);
            List<Integer> myList = (List<Integer>) ois.readObject();
            Log.d("chj", "onCreate: "+myList);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

2.文件读写

BufferedReader + FileReader//读文件
BufferedWriter + FileWriter//写文件
可以只用后者 不过效率低下
注意此处调用的是read,write方法

文件读写demo

public class FileTest {
		public static void main(String [] args){
			try {
				FileWriter writer = new FileWriter("foo.txt");
				BufferedWriter bu = new BufferedWriter(writer);
				bu.write("hello world \n sdssafsd \n dfsdfsdf啊啊哈哈");
				bu.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				FileReader reader = new FileReader("foo.txt");
				BufferedReader bu = new BufferedReader(reader);
				String s;
				while((s = bu.readLine())!= null){
					System.out.println(s);
				}
				bu.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}

3.socket通信

BufferedReader InputStreamReader//接受信息
PrintWriter//发送信息 注意此处 没有使用BufferedWriter+OutputStreamWriter
注意此处调用的BufferedReader的read方法,PrintWriter 的print和println方法,而非write(区别于上面的情况)

简单的Socket通信demo (demo为Head First Java socket一章的内容,如书中所说,本示例存在诸多bug和可以优化的地方)
运行顺序:先服务器,后客户端,客户端可以启动多个
客户端:

public class SimpleChatClientB {
	JTextArea incoming;// 收件框
	JTextField outgoing;// 发送框
	JButton button;// 确认框
	BufferedReader reader;
	PrintWriter writer;
	Socket socket;

	public static void main(String[] args) {
		SimpleChatClientB client = new SimpleChatClientB();
		client.go();
	}

	private void go() {
		// 初始化布局
		JFrame jFrame = new JFrame("Simple chat client");
		JPanel panel = new JPanel();
		
		incoming = new JTextArea(15, 30);
		incoming.setLineWrap(true);
		incoming.setWrapStyleWord(true);
		incoming.setEditable(false);
		JScrollPane qScrollPane = new JScrollPane(incoming);
		qScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		qScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		outgoing = new JTextField(20);

		button = new JButton();
		button.setText("Send");
		button.addActionListener(new SendButtonListener());

		panel.add(qScrollPane);
		panel.add(outgoing);
		panel.add(button);
		
		jFrame.getContentPane().add(BorderLayout.CENTER, panel);
		jFrame.setSize(400, 500);
		jFrame.setVisible(true);
		//end 布局
		
		// 设置端口号等连接信息
		setUpNetworking();
		
	   //启动服务器监听
		Thread readerThread = new Thread(new IncomingReader());
		readerThread.start();
	}

	private void setUpNetworking() {
		//设置端口号和IP 建立输入输出流
		try {
			socket = new Socket("127.0.0.1", 5001);
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new PrintWriter(socket.getOutputStream());
			System.out.println("network established");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public class SendButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			//Send监听
			//向Server发送数据
			writer.println(outgoing.getText());
			writer.flush();

			//界面更新
			outgoing.setText("");
			outgoing.requestFocus();
		}
	}
	
	public class IncomingReader implements Runnable{
		public void run() {
			String message;
			try {
				//持续监听从Server返回的数据
				while ((message = reader.readLine())!= null) {
					System.out.println("read :"+message);
					incoming.append(message+"\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

服务器:

public class VerySimpleChatServer {
	ArrayList<PrintWriter> clientOutputStreams;
	public static void main(String[] args) {
		System.out.println("Server Running");
		new VerySimpleChatServer().go();
	}
	private void go() {
		clientOutputStreams = new ArrayList<PrintWriter>();
		
		//服务器等待客户端注册端口
		ServerSocket serverSocket = null;
		try {
			 serverSocket = new ServerSocket(5001);
			while(true){
				//接受从客户端传来的socket
				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("got a connection");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	class ClientHandler implements Runnable{
		BufferedReader reader;
		Socket socket;
		
		public ClientHandler(Socket clientSocket){
			socket =clientSocket;
			//从客户端传来的socket读取信息
			try {
				reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public void run() {
			String message;
			try {
				while ((message = reader.readLine()) != null) {
					System.out.println("Server reading message:"+message);
					tellEveryone(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		private void tellEveryone(String message) {
			Iterator<PrintWriter> it = clientOutputStreams.iterator();
			//把收到的消息转发给所有客户端(包括发送者)
			while (it.hasNext()) {
				PrintWriter writer = it.next();
				writer.println(message);
				writer.flush();
			}
		}
		
	}

}

效果图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值