java - 从 Java 客户端发送的 servlet 中读取 File、String、Int

标签 java jsp jakarta-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 端**********

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 读取数据。

谢谢。

最佳答案

您的循环会一直循环,直到流为“空”为止,然后退出循环。但之后您尝试再次从流中读取数据,该流是空的并且您即将到达 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);
}

关于java - 从 Java 客户端发送的 servlet 中读取 File、String、Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11536043/

相关文章:

java - JBoss 启动期间出现问题

java - 圆形布局 : Cannot resolve method onCreate(android. os.Bundle)

java - 在中央存储库中找不到 Maven ojbc 6 jar

java - .war 与 .ear 文件

JAVA:对于更新和插入,我可以使用端点或 GET 请求来处理 servlet 中的数据吗

java - Linux 和 MySQL 中的编码问题

java - Spark数据集获取与整数列标题相同的数据

html - 如何使用迭代器变量设置 Struts2 下拉列表值

java - jsp和jsi有什么区别?

java - 系统日志 EJB Java EE