这是我的用于传输图像的客户端程序,在传输图像文件时它已经损坏,无法打开该图像文件,我无法识别错误,任何人都可以帮助我。
DataInputStream input = new DataInputStream(s.getInputStream());
DataOutputStream output = new DataOutputStream(s.getOutputStream());
System.out.println("Writing.......");
FileInputStream fstream = new FileInputStream("Blue hills.jpg");
DataInputStream in = new DataInputStream(fstream);
byte[] buffer = new byte[1000];
int bytes = 0;
while ((bytes = fstream.read(buffer)) != -1) {
output.write(buffer, 0, bytes);
}
in.close();
答案 0 :(得分:0)
我认为s
是Socket
并且您尝试通过网络传输文件?这是一个使用套接字发送文件的示例。它只是在一个线程中设置一个服务器套接字并连接到它自己。
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
FileOutputStream out = new FileOutputStream("out.jpg");
copy(in, out);
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
Socket socket = new Socket("localhost", 3434);
OutputStream out = socket.getOutputStream();
FileInputStream in = new FileInputStream("in.jpg");
copy(in, out);
out.close();
in.close();
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}