26. BufferedOutputStream的flush()方法

果然上机暴露的问题就是多。

今天复习到写TCP并发上传图片,但是复制出来的图片就是有一片灰色,复制不到。

浪费了半个下午加一晚上,又看书又看Buffered流的源码又上机逐行代码试,

最后实在不行去问别人,原来是因为flush()方法。

import java.io.*;
import java.net.*;

public class Server {
	public static void main(String[] args) throws UnknownHostException,
			IOException {

		ServerSocket ss = new ServerSocket(10003);
		Socket s = ss.accept();

		String IP = s.getInetAddress().getHostAddress();
		int count = 1;

		File file = new File("C:\\JavaFiles\\A\\" + IP + ".jpg");

		while (file.exists()) {
			file = new File("C:\\JavaFiles\\A\\" + IP + "_" + (count++)
					+ ".jpg");
		}

		InputStream in = s.getInputStream();
		OutputStream out = s.getOutputStream();

		BufferedInputStream bis = new BufferedInputStream(in);
		FileOutputStream fos = new FileOutputStream(file);
		BufferedOutputStream bos = new BufferedOutputStream(fos);

		byte[] buf = new byte[1024];
		int len = 0;
		int lenCount = 0;
		while ((len = bis.read(buf)) != -1) {
			System.out.println("A:" + len);// test
			bos.write(buf, 0, len);
			// bos.flush();
			lenCount = lenCount + len;
			System.out.println("B:" + lenCount);// test
		}

		System.out.println(lenCount);

	}
}

import java.io.*;
import java.net.*;

public class Client {
	public static void main(String[] args) throws UnknownHostException,
			IOException {

		if (args.length != 1) {
			System.out.println("Please entry fileName.");
			return;
		}
		File file = new File(args[0]);
		if (!file.exists()) {
			System.out.println("File is not existed.");
			return;
		}
		if (!file.getName().endsWith(".jpg")) {
			System.out.println("File is not a jpg file.");
			return;
		}
		if (file.length() > 1024 * 1024) {
			System.out.println("must more than 1M.");
			return;
		}

		Socket s = new Socket(InetAddress.getByName("localhost"), 10003);
		InputStream in = s.getInputStream();
		OutputStream out = s.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(fis);
		BufferedOutputStream bos = new BufferedOutputStream(out);

		byte[] buf = new byte[1024];
		int len = 0;
		int lenCount = 0;
		while ((len = bis.read(buf)) != -1) {
			// bos.write(buf,0,len);
			out.write(buf, 0, len);
			lenCount = lenCount + len;
		}
		System.out.println(lenCount);
		s.shutdownOutput();

		fis.close();
		bis.close();
		bos.close();
		// s.close();
	}
}

如果缓冲区操作最后那部分没有存满,既不flush()最后又不close()就会发生这种情况。

参考:为什么关闭一个缓冲区输出流之前应使用flush方法?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值