1
因此,我有一个处理连接请求的网络服务器,将整个请求存储到字符串(问题依赖于我相信的地方),在进行任何类型的处理。从服务器端读取二进制数据的Java serversocket(http)
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
// Loop here until there is no more to read, but wait until the first message arrives.
while (in.ready() || httpRequestString.isEmpty()) {
// Read one integer at the time and cast it to a character.
httpRequestString += (char) in.read();
}
然后将其发送到HttpRequest类来检查它,如果它是一个POST,将二进制数据保存到文件中。
可以正常使用文本文件,而不会使用损坏的二进制文件。
我知道你不应该一行一行地阅读二进制文件(特别是用扫描仪),并用printwriter写它,但我必须检查请求并寻找文件内容的起始和结束边界,因此我想出了快速的临时代码,只是去展示我的东西。
scanner = new Scanner(body);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("--" + boundary)) {
fileName = scanner.nextLine().split("filename=")[1].replaceAll("\"", "");
fileType = scanner.nextLine();
scanner.nextLine(); //empty line
PrintWriter fileOutput = new PrintWriter(rootFolder + File.separator + fileName);
//FileOutputStream fileOutput1= new FileOutputStream(new File(rootFolder + File.separator + fileName));
String prev = scanner.nextLine();
while (scanner.hasNextLine()){
String next = scanner.nextLine();
System.out.println("reading from: " + prev);
if (!(next.equals("--" + boundary + "--"))){
fileOutput.println(prev);
prev = next;
}
else {
fileOutput.print(prev);
break;
}
}
fileOutput.close();
}
}
scanner.close();
如何将一个存储在开始的整体要求,不松的过程中的任何字节,并能够检查的内容,从中提取二进制数据?
我不认为它会解决我的问题。我的猜测是我在将int转换为char时丢失了数据:httpRequestString + =(char)in.read(); –