服务器端:
import java.net.*;
import java.io.*;
public class server {
public static void main(String args[]) {
ServerSocket ss = null;
Socket s = null;
DataInputStream instrm = null;
FileOutputStream fileoutstrm = null;
byte buf[] = new byte[256];
int c = 0;
try {
ss = new ServerSocket(8888);
s = ss.accept();
instrm = new DataInputStream(s.getInputStream());
fileoutstrm = new FileOutputStream("/home/m04/test.jpg");
while ((c = instrm.read(buf, 0, 256)) != -1) {
fileoutstrm.write(buf, 0, buf.length);
}
fileoutstrm.close();
} catch (IOException err) {
System.out.println("err[" + err + "]");
} finally {
try {
if (instrm != null) instrm.close();
} catch (Exception err1) {
}
try {
if (instrm != null) instrm.close();
} catch (Exception err2) {
}
try {
if (ss != null) ss.close();
} catch (Exception err3) {
}
try {
if (s != null) s.close();
} catch (Exception err4) {
}
}
}
}
如果在同一台机器上传送图片没有问题,但如果在两台机器之间传送,就会出现传送后的文件会变大。应该怎样写呢??
import java.net.*;
import java.io.*;
public class server {
public static void main(String args[]) {
ServerSocket ss = null;
Socket s = null;
DataInputStream instrm = null;
FileOutputStream fileoutstrm = null;
byte buf[] = new byte[256];
int c = 0;
try {
ss = new ServerSocket(8888);
s = ss.accept();
instrm = new DataInputStream(s.getInputStream());
fileoutstrm = new FileOutputStream("/home/m04/test.jpg");
while ((c = instrm.read(buf, 0, 256)) != -1) {
fileoutstrm.write(buf, 0, buf.length);
}
fileoutstrm.close();
} catch (IOException err) {
System.out.println("err[" + err + "]");
} finally {
try {
if (instrm != null) instrm.close();
} catch (Exception err1) {
}
try {
if (instrm != null) instrm.close();
} catch (Exception err2) {
}
try {
if (ss != null) ss.close();
} catch (Exception err3) {
}
try {
if (s != null) s.close();
} catch (Exception err4) {
}
}
}
}
如果在同一台机器上传送图片没有问题,但如果在两台机器之间传送,就会出现传送后的文件会变大。应该怎样写呢??
while ((c = instrm.read(buf, 0, 256)) != -1) {
fileoutstrm.write(buf, 0, buf.length);
~~~~~~~~~~~~~这里有错
用fileoutstrm.write(buf,0,c)看看