如题,TCP方式 自己给自己传文件用来传文本文件为什么传到服务器端接收后就变成空的了 或者是一半文字然后几个乱码 这是什么情况?
图片视频等格式测试无问题,只有文本文件出问题. 按理说 字节流不是也可以传递文本的吗?..
系统是Mac OS 编码一直都默认的UTF-8
代码如下
客户端
- import java.io.*;
- import java.net.Socket;
- /**
- * Created by mo on 15/11/21.
- *
- * 需求:上传文件到服务器
- */
- public class Upload {
- public static void main(String[] args) throws IOException {
- Socket socket = new Socket("192.168.0.100",25255);
- BufferedInputStream br = new BufferedInputStream(new FileInputStream("/Users/mo/day26.txt"));
- BufferedOutputStream bw = new BufferedOutputStream(socket.getOutputStream());
- int len;
- byte[] arr = new byte[2048];
- while ((len=br.read(arr)) != -1){
- bw.write(arr,0,len);
- }
- //上传完了就给个结束标记,告诉服务器已经传完了,别等了
- socket.shutdownOutput();
- InputStream rec = socket.getInputStream();
- int end ;
- byte[] arr1 = new byte[1024];
- end = rec.read(arr1);
- System.out.println(new String(arr1,0,end));
- br.close();
- socket.close();
- }
- }
复制代码
服务器端
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * Created by mo on 15/11/21.
- */
- public class Server {
- public static void main(String[] args) throws IOException{
- ServerSocket serverSocket = new ServerSocket(25255);
- Socket s = serverSocket.accept();
- BufferedInputStream br = new BufferedInputStream(s.getInputStream());
- BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("day26.txt"));
- byte[] arr = new byte[2048];
- int len;
- while ((len=br.read(arr))!=-1){
- bw.write(arr,0,len);
- }
- OutputStream sd = s.getOutputStream();
- sd.write("文件上传完毕".getBytes());
- bw.close();
- s.close();
- }
- }
复制代码
|