Java I/O: How to append to an already existing text file - java

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.

Related

Byte array to File object without saving to disk

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).

JavaCC: parsing a string and not reading from stdin or from a file

i wrote a parser with JavaCC, which i can successfully test in eclipse reading the stream from standard input (keyboard). now i want to call this class with the parser from another class. the data to parse are available in a string. currently i didn't find a way to pass the string as argument. it's only possible to parse from stdin or from a file. writing the string to a file and than parsing the file is in my opinion not a solution.
any idea how to solve this issue ?
i can't believe that i am the only one who want's to analyze only a string and not a complete file.
kind regards
hans
--
You can construct the parser instance with an InputStream. This page shows you how to create the InputStream, How does one create an InputStream from a String?
Then you can construct your parser with this as defined in the JavaCC API.
TheParser.TheParser(java.io.InputStream stream)
Do notice though:
This constructor is available only when both the options USER_TOKEN_MANAGER and USER_CHAR_STREAM are false. If the option STATIC is true, this constructor (along with other constructors) can be called exactly once to create a single parser object.
https://javacc.java.net/doc/apiroutines.html
You set these options in the option_bindings. https://javacc.java.net/doc/javaccgrm.html

Java writing to File or System.out

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

How can I save information in an existing textfile in Java?

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);

Can I use Xuggler to encode video/audio to a byte array?

It seems all methods expect either files or urls. I see some methods that work with OutputStream, but I haven't managed to open an IContainer using one of those methods; I always get an invalid return value.
Create your own IURLProtocolHandler interface and pass to IContainer.open(...) to open any type of media type you want.
You can look at this answer I posted on another question to write to an OutputStream (which could easily be a ByteArrayOutputStream).
This gist of it would be to use com.xuggle.xuggler.io.XugglerIO to map from an OutputStream to a special kind of file URL so that FFMPEG can access the stream.
IMediaWriter writer = ToolFactory.makeWriter(XugglerIO.map(outputStream));
Keep in mind that you'll now have to manually set your format (because it can't detect it from the filename). For example:
IContainerFormat containerFormat = IContainerFormat.make();
containerFormat.setOutputFormat("ogg", null, "application/ogg");
writer.getContainer().setFormat(containerFormat);

Categories

Resources