从Java Client发送的servlet中读取File,String,Int

时间:2012-07-18 07:11:03

标签: java jsp java-ee servlets servlet-3.0

我正在从Java客户端程序向Servlet发送请求,如下所示,

URL url = new URL("http://localhost:8080/TestWebProject/execute");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

DataOutputStream out = new DataOutputStream(httpCon.getOutputStream());
out.writeUTF("hello");
out.writeUTF("World");

ByteArrayOutputStream bos;
File baseFile = new File("C:\\Users\\jp\\Desktop\\mdn.txt");

if (!baseFile.exists())
{
    System.out.println("File Not Found Correctly");
}

FileInputStream fis = new FileInputStream(baseFile);

byte[] fileBytes = new byte[1024];
bos = new ByteArrayOutputStream();

while (true)
{
    int ch = fis.read(fileBytes);

    if (ch != -1)
    {
        bos.write(fileBytes, 0, ch);
    }
    else
    {
        break;
    }
}
bos.close();
fis.close();

out.write(bos.toByteArray());

out.writeInt(10);

out.close();



* ** * ** * ** * SERVLET SIDE * ** * ** * ** * < / p>

InputStream is = (InputStream) req.getInputStream();

DataInputStream dis = new DataInputStream(is);
System.out.println("NAME US :" + dis.readUTF());
System.out.println("NAME US 1:" + dis.readUTF());

File f = new File("D:\\temp2.txt");
f.createNewFile();

FileOutputStream fos = new FileOutputStream(f);

byte[] fileBytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();

while (true)
{
    int ch = dis.read(fileBytes);

    if (ch != -1)
    {
        bos.write(fileBytes, 0, ch);
    }
    else
    {
        break;
    }
}
fos.write(bos.toByteArray());

System.out.println(dis.readInt());

我得到输出为 你好 世界 此外,文件已成功复制到上述位置temp2.​​txt

我在System.out.println(dis.readInt())行中遇到问题;随着EOF的到来。

我在哪里做错了,以及如何从DataInputStream中读取数据。

感谢。

1 个答案:

答案 0 :(得分:0)

你的循环循环直到你的流为“空”,然后你退出循环。但之后你再次尝试从流中读取,这是空的,你正在达到eof。 您要将哪些数据打印到sysout?

修改

您可以直接写入FileOutputStream并重写您的循环:

FileOutputStream fos=new FileOutputStream(f);

byte[] fileBytes=new byte[1024];
int ch;

while(((ch = dis.read(fileBytes)) != -1) {
   fos.write(fileBytes,0,ch);
}