//服务器端传来的文件中文显示不了,我知道是字节流的问题,可是我用字符流实现还是没有成功啊 请问怎么改 !!高手帮忙啊 !!!
//从服务器向客户端发送一个文件,客户端接收文件并保存
//Client端
import java.net.*;
import java.io.*;
public class TcpClient {
/**
* @param args从服务器向客户端发送一个文件,客户端接收文件并保存
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
while (true) {
Socket client = new Socket("10.33.0.9", 2222);
File f = null;
InputStream in = client.getInputStream();
int b = 0;
String str = "C:/";
while ((b = in.read()) != -1) {
str += (char) b;
}
f = new File(str);
f.createNewFile();
System.out.println("文件创建成功");
client.close();
Socket client1 = new Socket("10.33.0.9", 2222);
// InputStream ins = client1.getInputStream();
// System.out.println(str);
// DataInputStream ins = new
// DataInputStream(client.getInputStream());//不知道为什么这样就不行呢
// str = str+ins.readUTF();
int bc = 0;
BufferedInputStream buffin = new BufferedInputStream(
client1.getInputStream());// 将管道中的数据读入缓冲区
FileWriter fw = new FileWriter(f);
while ((bc = buffin.read()) != -1) {
fw.write(bc);
}
System.out.println("client over");
fw.close();
client1.close();
buffin.close();
}
}
}
//Server端
import java.net.*;
import java.io.*;
import java.util.*;
public class TcpServer {
/**
*
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
while (true) {
ServerSocket server = new ServerSocket(2222);
File f = new File("D:/JavaWorkspace/day12/src/TcpServer.java");
Socket socket = server.accept();
DataOutputStream dos = new DataOutputStream(
socket.getOutputStream());
System.out.println("请输入要传递的文件名");
Scanner in = new Scanner(System.in);
String path = in.next();// 文件名
if (path != null) {
dos.writeBytes(path);
}
dos.flush();
dos.close();
socket.close();
Socket socket1 = server.accept();
DataOutputStream dos1 = new DataOutputStream(
socket1.getOutputStream());
FileReader fr = new FileReader(f);
int b = 0;
while ((b = fr.read()) != -1) {
dos1.write(b);
}
System.out.println("server over");
dos1.flush();
dos1.close();
server.close();
socket1.close();
}
}
}
------解决方案--------------------
读写必须保持一致,既然你在服务器端写,是按照单个字符进行写的“dos1.write(b);”
那么客户端读取也就必须按相同方法单个字符进行读取。
你用readUTF(),编码肯定就错乱了。
不过,对于传输文件而言,一般建议读写直接用 byte[] 数组来做,效率高,且适用于任何文件类型,图片啥的都没问题。