Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java saving/opening File objects

Tags:

java

file-io

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?

like image 230
Richard Stokes Avatar asked Nov 22 '11 19:11

Richard Stokes


People also ask

How do you save a Java object file?

Open a new or an existing file using FileOutputStream . Create an instance of ObjectOutputStream and pass FileOutputStream as an argument to its constructor. Use ObjectOutputStream. writeObject() method to write the object to the file.

What are object files in Java?

Object Files are text based files supporting both polygonal and free-form geometry (curves and surfaces). The Java 3D . obj file loader supports a subset of the file format, but it is enough to load almost all commonly available Object Files.


2 Answers

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.

like image 115
Jesper Avatar answered Sep 28 '22 01:09

Jesper


You should look into Data Handlers

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

like image 32
Cratylus Avatar answered Sep 28 '22 00:09

Cratylus