【发布时间】:2014-07-27 12:52:23
【问题描述】:
如何从服务器端代码接收原始内容和文件名。 客户代码
public void send1(Socket socket)
{
try
{
dataOutputStream = new DataOutputStream(socket.getOutputStream());
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "temp.txt");
FileInputStream fis = new FileInputStream(file);
//write file length
dataOutputStream.writeLong(file.length());
Log.i("File Size", "" + file.length());
//write file names
dataOutputStream.writeUTF(file.getName());
Log.i("File Name", "" + file.getName());
//write file to dos
byte[] buf = new byte[4092];
int n = 0;
while((n = fis.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
dataOutputStream.write(buf, 0, n);
}
dataOutputStream.flush();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
文件名为temp.txt,内容为Hello
服务器代码
public void receive1(Socket socket)
{
try
{
inputStream = socket.getInputStream();
dataInputStream = new DataInputStream(inputStream);
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
int n = 0;
byte[] buf = new byte[4092];
//read file name
/*String fileName = "";
try
{
fileName = dataInputStream.readUTF();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Name", "" + fileName);*/
//read file size
long fileSize = 0;
try
{
fileSize = dataInputStream.readLong();
}
catch (Exception e)
{
e.printStackTrace();
}
Log.i("File Size", "" + fileSize);
//read file
while((n = dataInputStream.read(buf)) != -1)
{
Log.i("length bytes", "" + n);
fos.write(buf, 0, n);
}
fos.flush();
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
文件名为test.txt,内容为temp.txtHello。
在这个test.txt 文件中,包含temp.txt。我没有从dataInputStream.readUTF() 获取文件名。
我在哪里弄错了代码...
如果我调用了readUTF() 方法,那么我得到了异常
异常为
java.io.EOFException
at libcore.io.Streams.readFully(Streams.java:83)
at java.io.DataInputStream.readFully(DataInputStream.java:99)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:178)
at java.io.DataInputStream.decodeUTF(DataInputStream.java:173)
at java.io.DataInputStream.readUTF(DataInputStream.java:169)
【问题讨论】:
-
您没有调用 readUTF(),除非在注释掉的代码中。你期待什么?
-
@EJB 如果我调用 readUTF(),我会收到
java.io.EOFException -
假设你贴出真实的代码,以及真实的异常?
标签: android sockets inputstream outputstream