java将字符串和文件发送到InputStream
我试图发送一个字符串,它是文件名,然后文件本身发送到服务器。服务器正在接收该字符串并将其用于创建文件。但是,服务器没有实际写入文件的任何数据
在我向服务器和客户机添加写入程序(文件名是硬编码的)之前,我已经完成了文件传输,但现在我无法让这两个程序同时工作
客户:
public class Client {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
while (true) {
String fileName = sc.nextLine();
System.out.println(fileName);
try {
File file = new File(fileName);
Socket socket = new Socket("localhost", 15000);
OutputStream os = socket.getOutputStream();
Writer w = new OutputStreamWriter(os, "UTF-8");
w.write(fileName);
w.close();
os.flush();
byte[] mybytearray = new byte[(int) file.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
bis.read(mybytearray, 0, mybytearray.length);
os.write(mybytearray, 0, mybytearray.length);
os.flush();
os.close();
socket.close();
} catch (Exception e) { }
}
}
}
服务器:
public class Server extends Thread {
public static final int PORT = 15000;
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket sock = serverSocket.accept();
readFile(sock);
}
} catch (Exception e) {
}
}
private void readFile(Socket socket) throws Exception {
InputStream ois = socket.getInputStream();
Reader r = new InputStreamReader(ois, "UTF-8");
String filename = "";
int ch = r.read();
while(ch != -1) {
filename += (char) ch;
System.out.println(filename);
ch = r.read();
}
r.close();
System.out.println(filename);
FileOutputStream fos = new FileOutputStream(filename);
byte[] bytearr = new byte[4096];
System.out.println("Reading file...");
BufferedOutputStream bos = new BufferedOutputStream(fos);
while ((ois.read(bytearr)) > 0) {
bos.write(bytearr);
}
bos.close();
System.out.println("Writing file complete...");
}
public static void main(String[] args) {
new Server().start();
}
}
# 1 楼答案
这是我的解决方案,此方法需要一些改进:
说明:
基本上,我一次将所有信息发送到服务器(这是您需要了解的一个改进)
另一个改进是按块发送文件,而不是一次发送所有文件
客户端类:
服务器类:
希望这有帮助强>
编码时间快乐
# 2 楼答案
您还需要关闭文件Ouptut流。与
加