我正在从 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/