how to do Serializtionf of a file - java

i have a xml file named as default xml with sample contents as
<check>hi</check>
in my application i am doing an operation such that it wil operate on the xml and writes the new value to it, by overriding the newvalue on the oldone
ex:
<check>hi updated</check>
and i closed my application now
my problem is here:
whenever i start application again i should get the contents of default xml as
<check>hi<check>
instead of
<check>hi updated</check>
how can i achieve this ,can i have an steps to implement this r any sample code to implement this
i wil b thankful to ur valuable replies

Um... don't overwrite the file then? Keep the changes in memory or work on a temporary copy.

Writing data:
FileOutputStream os = new FileOutputStream("C:/cust.xml");
XMLEncoder encoder = new XMLEncoder(os);
Person p = new Person();
p.setFirstName("John");
encoder.writeObject(p);
encoder.close();
Reading data:
FileInputStream os = new FileInputStream("C:/cust.xml");
XMLDecoder decoder = new XMLDecoder(os);
Person p = (Person)decoder.readObject();
decoder.close();
EDIT: You can also use XStream library. Here will you find a complete tutorial about it

Related

How can I deleting the content of a file without deleting it self?

I want to clear the content of a file witch have a specific extension file.tctl, i don't want to change any thing about the file neither deleting it. The file is generated from a specific model checker so that i have just to delete the content and write my own. I tried to print an empty string like that:
PrintWriter writer = new PrintWriter(file.tctl);
writer.print("");
writer.close();
but the file doesn't work any more. So if there's another method to clear the content of the file.
Just remove the print altogether from your code. You've already truncated the file with the new FileOutputStream/PrintWriter/ whatever you use to open it. No I/O or truncate() necessary. Don't use append mode.
Most easy way I guess
new RandomAccessFile("filename.ext", "rw").setLength(0);
Call your write() method like this:
.write((new String()).getBytes());
This will make your file empty. If that doesn't works, try with this:
FileOutputStream erasor = new FileOutputStream("filename.ext");
erasor.write((new String()).toByteArray());
erasor.close();
Or just try to overwrite the file
//open file in override mode
FileOutputStream out = new FileOutputStream("filename.ext");
//now anything that we write here will remove the old one so just write space ("") here
You have to use a FileOutputStream and then you have the truncate() method:
File f = new File("path-of-the-file.here");
FileChannel channel = new FileOutputStream(f, true).getChannel();
channel.truncate(0);
channel.close();

using FileInputStream and FileOutputStream

Hi I had a couple of questions about using the FileInputStream and FileOutputStream classes.
How would FileInputStream objects locate a file it is trying to read in?
Where would FileOutputStream save a file to?
Thanks.
Strange question and I will give a strange answer.
First part: don't use either, use Files:
final Path src = Paths.get("some/file/somewhere");
final InputStream in = Files.newInputStream(src);
// ...
final Path dst = Paths.get("another/file");
final OutputStream out = Files.newOutputStream(dst);
Note that Path objects are in essence abstract: nothing guarantees that they point to a valid entry. If they don't, the Files methods above will throw a NoSuchFileException (file does not exist), or an AccessDeniedException (sorry mate, you can't do that), or any relevant exception.
Second part: File*Stream
The basics are the same: if you are stuck with Java 6 you have to use File instead of Path, but File is as abstract as Path is; it may, or may not, point to a valid location.
When you issue:
final String dst = "/some/file";
new FileOutputStream(dst);
internally, FileOutputStream will create a File object; which means the above is equivalent to:
final String dst = "/some/file";
final File f = new File(dst);
new FileOutputStream(f);
Conclusion: no, File*Stream does not know per se whether a file exists as long as it does not try to open it. Paths as well as Files are completely abstract until you try and do something with them.
And do yourself a favour: use the new file API which Java 7+ provides. Have you ever tried to initiate a FileInputStream with a File which exists but you cannot read from? FileNotFoundException. Meh. Files.newInputStream() will at least throw a meaningful exception...
Generally, you simply pass the file object to the stream instantiations.
FileInputStream is = new FileInputStream(f);
FileOutputStream os = new FileOutputStream(f);
BufferedInputStream is2 = new BufferedInputStream(is);
BufferedOutputStream os2 = new BufferedOutputStream(os);
Also consider using Printwriter for the output stream when you are working with text files.
About Streams:
Streams are objects that allow an app to communicate with other programs.
To directly answer your question, in Java, here is how I would use the Streams.
//You need to import a few classes before you begin
import java.io.FileInputStream;
import java.io.FileOutputStream;
You can declare them this way
FileInputStream is = new FileInputStream("filename.txt"); //this file should be located within the project folder
For output stream, it can be accessed a similar way:
FileOutputStream os = new FileOutputStream("filename.txt"); //this file should be located within the project folder
More Information:
I recommend using a PrintWriter when trying to write to text files. To do this, you would implement the following:
import java.io.PrintWriter;
Then use this to write to the file:
PrintWriter pw = new PrintWriter(OUTPUT_STREAM);
I also recommend using the Scanner class when reading in user data:
import java.util.Scanner;
Then use this to read the input:
Scanner kb = new Scanner(INPUT_STREAM); //now you can access this data by using methods such as nextInt, nextDouble, etc...

Reading updated values from a .config file

I'm having some trouble when reading from a .config file in a Java application.
I have a module, let's call it Configuration_Reader that implements the next interface:
Interface
int getDelayValue();
int getRepValue();
...
For example, the getDelayValue() implementation is as follows:
Implementation
InputStream fis = new FileInputStream(
new File("").getAbsolutePath()+"/config/config.properties");
props.load(fis);
fis.close();
PropertyConfigurator.configure(props);
...
public int getDelayValue() {
return getIntProperty("delayValue");
}
There's no error nor exception when reading the value, but my issue is that if I update the value on the config file and call the getDelayValue() function again, it always returns the original value the property had when I launched the application. So, it is not updating (I assume it is not reading the file again) even if debugging I can see that the function is being called appropriately.
Any tips? Thanks in advance
You need to reload the config file to see the changes, i.e. this code
InputStream fis = new FileInputStream(
new File("").getAbsolutePath()+"/config/config.properties");
props.load(fis);
fis.close();
PropertyConfigurator.configure(props);
needs to run again, after the config has changed.
If you're using Java 7 you can use a WatchService to detect if the file has changed.
Another alternative would be to reload the config file every time a config value is accessed, but I wouldn't recommend this if the value is accessed frequently or concurrently from multiple threads.

Understanding flow of object creation

I'm new to java and I wonder if there is simple way to know flow like the following of object creation, I'm using eclipse and when I write new ObjectInputStream and press CTRL+SPACE.
I don't see any option that I can enter new BufferedInputStream (I have copied the code from example) and than to create new object for FileInputStream etc.
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("emp.dat")));
List temp = (List)in.readObject();
I give that example since this is the first time that I saw this kind of creation new object flow and I want to use some best practice for the next times.
This is a classic example of using [Decorator Pattern][1]. You will wrap objects to add behavior.
This is very simple. This is equivalent to :
FileInputStream fis = new FileInputStream("emp.dat");
BufferedInputStream bis = new BufferedInputStream(fis)
ObjectInputStream in = new ObjectInputStream(bis);
As you are new to Java, you should check javadocs instead of checking it in Eclipse.
Check : FileInputStream, BufferedInputStream, ObjectInputStream
Ctrl+Space shows you options you have available at that point to get the options you might value if you created something you have to type new and then Ctrl+Space
BTW: ObjectInputStream and ObjectOutputStream are already buffered so adding more buffering isn't best practice IMHO.

How to create a java.io.File from a ByteArrayOutputStream?

I'm reading a bunch of files from an FTP. Then I need to unzip those files and write them to a fileshare.
I don't want to write the files first and then read them back and unzip them. I want to do it all in one go. Is that possible?
This is my code
FTPClient fileclient = new FTPClient();
..
ByteArrayOutputStream out = new ByteArrayOutputStream();
fileclient.retrieveFile(filename, out);
??????? //How do I get my out-stream into a File-object?
File file = new File(?);
ZipFile zipFile = new ZipFile(file,ZipFile.OPEN_READ);
Any ideas?
You should use a ZipInputStream wrapped around the InputStream returned from FTPClient's retrieveFileStream(String remote).
You don't need to create the File object.
If you want to save the file you should pipe the stream directly into a ZipOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
// do whatever with your zip file
If, instead, you want to open the just retrieved file work with the ZipInputStream:
new ZipInputStream(fileClient.retrieveFileStream(String remote));
Just read the doc here and here
I think you want:
ZipInputStream zis = new ZipInputStream( new ByteArrayInputStream( out.toByteArray() ) );
Then read your data from the ZipInputStream.
As others have pointed out, for what you are trying to do, you don't need to write the downloaded ZIP "file" to the file system at all.
Having said that, I'd like to point out a misconception in your question, that is also reflected in some of the answers.
In Java, a File object does no really represent a file at all. Rather, it represents a file name or *path". While this name or path often corresponds to an actual file, this doesn't need to be the case.
This may sound a bit like hair-splitting, but consider this scenario:
File dir = new File("/tmp/foo");
boolean isDirectory = dir.isDirectory();
if (isDirectory) {
// spend a long time computing some result
...
// create an output file in 'dir' containing the result
}
Now if instances of the File class represented objects in the file system, then you'd expect the code that creates the output file to succeed (modulo permissions). But in fact, the create could fail because, something deleted the "/tmp/foo", or replaced it with a regular file.
It must be said that some of the methods on the File class do seem to assume that the File object does correspond to a real filesystem entity. Examples are the methods for getting a file's size or timestamps, or for listing the names in a directory. However, in each case, the method is specified to throw an exception if the actual file does not exist or has the wrong type for the operation requested.
Well, you could just create a FileOutputStream and then write the data from that:
FileOutputStream fos = new FileOutputStream(filename);
try {
out.writeTo(fos);
} finally {
fos.close();
}
Then just create the File object:
File file = new File(filename);
You need to understand that a File object doesn't represent any real data on disk - it's just a filename, effectively. The file doesn't even have to exist. If you want to actually write data, that's what FileOutputStream is for.
EDIT: I've just spotted that you didn't want to write the data out first - but that's what you've got to do, if you're going to pass the file to something that expects a genuine file with data in.
If you don't want to do that, you'll have to use a different API which doesn't expect a file to exist... as per Qwerky's answer.
Just change the ByteArrayOutputStream to a FileOutputStream.

Categories

Resources