我试图在android客户端上的文件中写一个byte [](加密文本),然后将此文件发送到服务器(使用HTTP)。该文件在移动设备中正确创建,但当它存储在服务器端时,它会创建一个0字节的文件。
这里是编写文件的android代码
File file = new File(getExternalCacheDir(), "index.txt");
FileOutputStream fout = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(encIndex);
oos.close();
这是用于读取和存储文件的servlet代码
String fileName = request.getHeader("fileName");
File saveFile = new File(SAVE_DIR + fileName);
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
FileOutputStream outputStream = new FileOutputStream(saveFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
System.out.println("File written to: " + saveFile.getAbsolutePath());
file.close();
客户端到服务器文件发送的代码
File uploadFile = new File(filePath, fileName);
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("fileName", uploadFile.getName());
OutputStream outputStream = httpConn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
由于某些原因,我无法使用Socket。 android没有显示任何错误。服务器显示的错误是,文件为空/我在空文件
上操作答案 0 :(得分:0)
fout.write(encIndex);
fout.close();
或者
BufferedOutputStream oos = new BufferedOutputStream(fout,
Math.min(4086, encIndex.length));
oos.write(encIndex);
oos.close();
答案 1 :(得分:0)
问题在于,我发送了更多带URL的数据,即https://ip:8084/project/servelt?reqid=something&data=something,
代码,不知何故,不允许我先读取参数,我需要先读取文件,然后再从URL中读取参数......
Jean和Joop,谢谢你的建议。