HTTP는 더 나은 선택이 될 것입니다,하지만이 직렬화 트릭을 시도했다 :
import java.io.*;
public class FileContent implements Serializable {
private transient File file;
public FileContent() {
}
public FileContent(File file) {
this.file = file;
}
private void writeObject(ObjectOutputStream out) throws IOException {
// 1. write the file name
out.writeUTF(file.getAbsolutePath());
// 2. write the length
out.writeLong(file.length());
// 3. write the content
final InputStream in = new BufferedInputStream(new FileInputStream(file));
final byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
out.flush();
in.close();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
// 1. read the file name
final String path = in.readUTF();
// 2. read the length
long remaining = in.readLong();
// 3. read the content
file = new File(path);
final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
final byte[] buffer = new byte[1024];
while (true) {
int length = in.read(buffer, 0, (int) Math.min(remaining, buffer.length));
if (length == -1) break;
out.write(buffer, 0, length);
remaining -= length;
if (remaining <= 0) break;
}
out.flush();
out.close();
}
}
은 가능한 경우 HTTP가 더 나은 옵션이 될 것이라는 데 동의했지만, 귀하가 가진 Externalizable 솔루션은 꽤 좋았으며 실제로 잘 작동하는 것으로 보았습니다. 파일의 내용은 메모에 나와 있듯이 메모리에 저장되지 않습니다. 위의 코드는 메모리 문제를 일으키지 않고 임의 크기의 파일을 효율적으로 스트리밍합니다. IO 스트림이 닫히지 않도록 try/finally가 부족합니다. –
내가 대답 한 것처럼 [rmiio] (http://openhms.sourceforge.net/rmiio/) 라이브러리는이 개념을보다 성숙한 구현 방식으로 제공합니다 (File뿐 아니라 모든 InputStream으로 일반화되어 있습니다). 즉석 압축 지원). 이 예제의 또 다른 문제점은 클라이언트와 서버에서 동일한 파일 이름이 유효하다고 가정한다는 것입니다. – jtahlborn
@jtahlborn 메모 주셔서 감사. 나는 RMIIO에 대해 인식하지 못했다. 환상적인 도서관처럼 들린다. 내 Externalizable 메모가 오래된 것 같습니다. 이것은 JDK 1.2 일 안에 다시 돌아가는 방식입니다.그들이 어떤 점에서 그것을 제거한 것처럼 보입니다. 그것은 환상적입니다. –