robbin,问一个socket和io方面的问题
我现在要从一台server通过tcp得到一个数据文件,server端给我传过来的数据内容是:
200 OK(表示有这个文件)
FILESIZE 1496124(数据文件的大小)
紧接着就是我要的到的数据文件
我的代码如下
public class getTar {
private FileWriter os = null;
/**
* set filename
* @param s
* @return
*/
public boolean setFilename(String s) {
try {
File f1 = new File(s);
if (f1.exists())
f1.delete();
os = new FileWriter(f1);
} catch (IOException e) {
return (false);
}
return (true);
}
/**
* get database file and save
* @param in
* @param FormSize
* @param os
*/
public void saveByte(InputStream in, int FormSize, FileWriter os) {
int i = 0;
DataInputStream is;
byte t;
try {
is = new DataInputStream(in);
while (i < FormSize) {
try {
t=is.readByte();
os.write(t);
i++; System.out.println("echo=" + i);
} catch (EOFException e) {
break;
}
}
is.close();
os.close();
} catch (IOException e) {
System.err.println("fault!");
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("fault!");
}
}
/**
* tar database and get database file
*
*/
public void getTar() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
int FileSize = 0;
try {
echoSocket = new Socket("192.168.0.111", 2001);
out = new PrintWriter(echoSocket.getOutputStream(), true);
InputStream ist = echoSocket.getInputStream();
in = new BufferedReader(new InputStreamReader(ist));
String echooutput;
String getTar = "get 文件名";
out.println(getTar);
System.out.println(getTar);
int i = 0;
while (((echooutput = in.readLine()) != null) && i < 2) {
System.out.println("echo: " + echooutput);
if (i == 1) {
FileSize = Integer.parseInt(echooutput.substring(9));
System.out.println("echo: " + FileSize);
}
i++;
}
this.saveByte(ist, FileSize, os);
System.out.println("操作成功!");
out.close();
in.close();
echoSocket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (Exception e) {
System.err.println(
"Couldn't get I/O for " + "the connection to: taranis.");
System.exit(1);
}
}
public static void main(String[] args) {
getTar Tar1 = new getTar();
Tar1.setFilename("文件名");
Tar1.getTar();
}
}
我接受的文件大小是1496124
可是我的程序输出老是到echo=1481292或echo=1487139附近就停下了,我试好多次都是这样,帮忙看看是咋会事?
或者大概说一说java的io操作,我的理解java的io操作使用的是decorate模式,象接水管似的,imputstream(字节流)外面套一个InputStreamReader(具体的字符),但是有一个问题了,比如我想取字符用了InputStreamReader,然后我又想取字节了,怎麽办.用在imputstream取到的是不是我预期的字符后面的东西.
头疼死我了!
帮帮忙,多谢了