8

After painstakingly trying to implement TCP file transfer in my conference chat application using raw byte streams, I've decided it's much easier to send files that I want transferred through object streams. The files are sent and stored at their destination (whether that is the central server or the downloading client) as in-memory File objects. However, these files are no use as just File objects - clients should be able to open them. Is there a way in java to save File objects as hard-disk files or to even open them up through Java?

Richard Stokes
  • 3,532
  • 7
  • 41
  • 57

3 Answers3

10

What do you mean with "File objects"; do you mean java.io.File?

Class java.io.File is just a representation of a directory name and filename. It is not an object which can hold the contents of a file.

If you have the data in for example a byte array in memory, then yes, you can save that to a file:

byte[] data = ...;

OutputStream out = new FileOutputStream(new File("C:\\someplace\\filename.dat"));
out.write(data);
out.close();

See the Basic I/O Lesson from Oracle's Java Tutorials to learn how to read and write files with a FileInputStream and FileOutputStream.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

You should look into Data Handlers

You can use them to transfer files as Data Sources but in a "transparent" way to you.

Cratylus
  • 52,998
  • 69
  • 209
  • 339
0

I've decided it's much easier to send files that I want transferred through object streams."

It isn't. Bad idea: costs memory and latency (i.e. time and space). Just send and receive the bytes, with stuff in front to tell you the filename and file size.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I tried sending the filename first using a PrintWriter, and then the raw bytes using a BufferedOutputStream. The filename and bytes would send from the sender side no problem. The receiver side could also receive the file name, however it could not receive any of the raw bytes - it just made empty files. When I switched to using an object stream, it seemed to work? – Richard Stokes Nov 23 '11 at 01:37
  • 1
    @RichardStokes That will never work. Use the same streams at both ends for the life of the connection. PrintWriter has a buffer, BufferedOutputStream has a buffer, BufferedReader has a buffer, and BufferedInputStream has a buffer. Too many buffers for coherence across the wire. I would use a DataOutputStream/DataInputStream for everything, sending the filename with writeUTF()/readUTF(), the length with writeLong()/readLong(), and the data with write() and read(). – user207421 Nov 23 '11 at 02:10