If you work with FileOutputStream methods, each time you write your file through this methods you've been lost your old data. Is it possible to write file without losing your old data via FileOutputStream?
Use the constructor that takes a File and a boolean
FileOutputStream(File file, boolean append)
and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
Related
I have a method that takes in a byte[] that came from Files.readAllBytes() in a different part of the code for either .txt or .docx files. I want to create a new File object from the bytes to later read contents from, without saving that file to disk. Is this possible? Or is there a better way to get the contents from the File bytes?
That's not how it works. a java.io.File object is a light wrapper: Check out the source code - it's got a String field that contains the path and that is all it has aside from some bookkeeping stuff.
It is not possible to represent arbitrary data with a java.io.File object. j.i.File objects represent literal files on disk and are not capable of representing anything else.
Files.readAllBytes gets you the contents from the bytes, that's.. why the method has that name.
The usual solution is that a method in some library that takes a File is overloaded; there will also be a method that takes a byte[], or, if that isn't around, a method that takes an InputStream (you can make an IS from a byte[] easily: new ByteArrayInputStream(byteArr) will do the job).
If the API you are using doesn't contain any such methods, it's a bad API and you should either find something else, or grit your teeth and accept that you're using a bad API, with all the workarounds that this implies, including having to save bytes to disk just to satisfy the asinine API.
But look first; I bet there is a byte[] and/or InputStream variant (or possibly URL or ByteBuffer or ByteStream or a few other more exotic variants).
I need to write characters to a file or to standard output. And I am curious if it could be done with one method.
Now I have something like this:
OutputStream out;
if(toConsole)
out = System.out;
else
out = new FileOutputStream(file);
write(out);
}
void write (OutputStream str){
....
str.write(string);
But it is a problem that I am using (in case when "str" is System.out) write instead print?
(print java doc: "string's characters are converted into bytes according to the platform's default character encoding")
In case if I would use PrintWriter(or PrintStream) as a parameter then i cannot use BufferedWriter and writing to the file would be slower.
It is possible to use a same code (and same methods) for writing to a file and to System.out?
(This is for my school project so I want it to be a "pure" and fully correct)
What you're trying to accomplish, is to treat the fileoutput and the consoleoutput the same. This is possible, because System.out is a PrintStream, and you can create a PrintStream for a file like this
new PrintStream(yourFile)
or insert a BufferedOutputStream in between
new PrintStream(new BufferedOutputStream(new FileOutputStream(yourFile))).
Note that this is not needed, because PrintStream does buffer its output itself.
I would create a variable (global or not), representing the current output.
This might be a PrintStream, either System.out, or a PrintStream around a FileOutputStream, whatever you desire. You would then pass this stream to the write method or call the print methods on it directly.
The advantage is that you can easily switch this without much code modification, you can redirect it wherever you wan't. It's no problem to redirect it to a file and System.out! You wouldn't get that pure flexibility with the way you're writing the method currently.
You could (not saying you should), also redirect System.out directly, using System.setOut. This however is bad style, because it is quite uncommon and might confuse everyone else, if they have not seen the call to System.setOut.
System.out is an object of type PrintStream. So yes, you can write to
System.out and/or to another file using exactly the same methods. Just
construct a PrintStream object and direct it to your file. So declare
your out variable as PrintStream to start with.
See also:
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html
http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html
I have the following methods that creates and writes to that file.
// Create the file and the PrintWriter that will write to the file
private static PrintWriter createFile(String fileName){
try{
// Creates a File object that allows you to work with files on the hardrive
File listOfNames = new File(fileName);
PrintWriter infoToWrite = new PrintWriter(new BufferedWriter(
new FileWriter(listOfNames);
return infoToWrite;
}
// You have to catch this when you call FileWriter
catch(IOException e){
System.out.println("An I/O Error Occurred");
// Closes the program
System.exit(0);
}
return null;
}
The program works fine, even if I dont have bufferedWriter and FileWriter like below. how does they two objects help in making the writing process better? I can avoid creating two objects in this case.
PrintWriter infoToWrite = new PrintWriter((listOfNames);
BufferedWriter
In general, a Writer sends its output immediately to the underlying
character or byte stream. Unless prompt output is required, it is
advisable to wrap a BufferedWriter around any Writer whose write()
operations may be costly, such as FileWriters and OutputStreamWriters.
If you're writing large blocks of text at once (like entire lines)
then you probably won't notice a difference. If you have a lot of code
that appends a single character at a time, however, a BufferedWriter
will be much more efficient.
you may refer to the API document and you'll find the difference:
BufferedWriter:Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
FileWriter:Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
if you want to create a file, the FileWriter will be better.
I want to save information in a textfile I already created. At school we only learnt to create a new one and save information in it.
How can I acheive this?
Thanks in advance
By default, if you create a FileOutputStream or FileWriter, it will just overwrite the existing text file - so if that's what you want to do, you're fine already.
If you want to append to a file, use the overload of the constructors for either of those types which takes a boolean parameter to indicate append/overwrite:
FileOutputStream output = new FileOutputStream("data.txt", true);
If you have been using FileWriter, by the way, I'd advise you to stop doing so - instead use FileOutputStream wrapped in an OutputStreamWriter. This allows you to specify the encoding you want to use, instead of always using the platform default encoding.
FileWriter fw = FileWriter(new File(pathToFile), true);
fw.write(stringToWrite);
Hi I am having no problem writing to or appending to a file, the only problem is that as soon as I quit the program and then run it again, it creates a new file overwriting my original file. This is a problem, as I am using the text file to keep a running tally.
Is there a way to get an already created text file as an object and then append to it?
Thanks in advance.
Usually, better than FileWriter (already suggested) is to use FileOutputStream, which also (like FileWriter ) has an append parameter in one of its constructors, and which (unlike FileWriter), does not silently assume the default charset encoding (slightly bad practice IMO).
From the FileWriter doc:
Convenience class for writing
character files. The constructors of
this class assume that the default
character encoding and the default
byte-buffer size are acceptable. To
specify these values yourself,
construct an OutputStreamWriter on a
FileOutputStream.
There is a constructor for FileWriter which allows you to set appending with a boolean.
javadoc
Take a look at java.io.FileWriter. Setting append to true should do the trick.