黑马程序员技术交流社区
标题:
网络编程部分,为什么上传图片大小变化了...求找错!
[打印本页]
作者:
杨浩
时间:
2013-1-22 23:28
标题:
网络编程部分,为什么上传图片大小变化了...求找错!
本帖最后由 杨浩 于 2013-1-28 16:38 编辑
package tcpdemo;
import java.io.IOException;
import java.net.*;
public class UploadPicServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10001);
while(true){
Socket s = ss.accept();
new Thread(new UploadTask(s)).start();
}
//ss.close();
}
}
复制代码
package tcpdemo;
import java.io.*;
import java.net.*;
public class UploadTask implements Runnable {
private Socket s;
public UploadTask(Socket s){
this.s = s;
}
public void run(){
int count = 0;
String ip = s.getInetAddress().getHostAddress();
try{
InputStream in = s.getInputStream();
File dir = new File("png");
if(!(dir.exists())){
dir.mkdirs();
}
File file = new File(dir,ip+".png");
while(file.exists()){
file = new File(dir,ip+"("+(++count)+").png");
}
FileOutputStream fops = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while ((len=in.read(buf))!=-1){
fops.write(buf, 0, len);
}
OutputStream out = s.getOutputStream();
out.write("传输完毕!".getBytes());
fops.close();
s.close();
}catch(Exception e){
System.out.println("ERROR!");
}
}
}
复制代码
package tcpdemo;
import java.io.*;
import java.net.*;
public class UploadPicClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("192.168.0.100",10001);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
File file = new File("1.png");
FileInputStream fins = new FileInputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while((len=fins.read(buf))!=-1){
out.write(buf, 0, buf.length);
}
s.shutdownOutput();
byte[] bufin = new byte[1024];
in.read(bufin);
System.out.println(new String(bufin,0,bufin.length));
fins.close();
s.close();
}
}
复制代码
服务端接收到的图片,大小会变化,而如果把服务端接收到的图片当作源的话,那么就一样大了...
难道是因为文件末尾多了字符么?
作者:
杨浩
时间:
2013-1-28 01:07
这么几天了,也没人解答,后来自己找到错误地方了。
是写入的时候,当作缓冲区的数组,输出的时候,参数不能写成buf.length,而应该是len
错误的地方在第三个文件的第16行
作者:
郭孟涛
时间:
2013-1-28 01:49
原来是输出的时候参数用错了,那实际寸的图片大小是没错的。 我刚刚开始学java,先来跟您学习了。
我觉得处理图片方面还是一个很复杂的知识
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2