Android: Difference between FileOutputStream and FileWriter - java

I was wondering what the exact difference is between Android's FileOutputStream and FileWriter class. When would it be most appropriate to use each one?

If I remember correctly, FileOutputStream is more general purpose - it can be used for binary data or text data. FileWriter is used for text only.
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/FileWriter.html
FileWriter is meant for writing streams of characters. For writing
streams of raw bytes, consider using a FileOutputStream.

Related

When should we use BufferedInputStream,FileInputStream or DataInputStream? [duplicate]

This question already has answers here:
Should I use DataInputStream or BufferedInputStream
(7 answers)
Closed 5 years ago.
I'm confused the above mentioned classes. When to use what? From my perspective every thing that comes in, is in the form of stream in java right? so which one is to use in what case to make the input more efficient? Also answer please can I use DataInputStream or BufferedInputStream in case of reading content from files?
FileInputStream
Is used for reading from files.
See the JavaDoc:
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. [...]
DataInputStream
Is used for reading in primitive Java types (that you might have written using a DataOutputStream) and provides convenience methods for that purpose, e.g. writeInt().
See the JavaDoc:
A data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way. [...]
BufferedInputStream
Is used to do buffered block reads from an InputStream (instead of single bytes) and increases performance if reading small chunks of data. Most of the time you want to use it for text processing.
See the JavaDoc:
A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input[...].
Of course you can combine those as they are following the Decorator Pattern.
Example of writing primitive Java types to a file:
FileOutputStream write = new FileOutputStream
DataOutputStream out = new DataOutputStream(write);
out.writeInt(10);
write.close();

Count the bytes written to file via BufferedWriter

I am using BufferedWriter to write text with specific encoding to file, I want to count the file size in bytes before I close the file.
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),encoding),bsize);
bw.write(string);
My plan was to use string.getBytes() but this method doesn't allow to provide specific encoding (and I can't override the default encoding property).
Use String#getBytes(encoding) instead
If you're looking for a method that works regardless of whether you're appending or not and does not duplicate data just for counting, store the reference to the FileOutputStream in a variable and access the FileChannel through getFileChannel(). You can call long position() before and after the data has been written, and the difference of the values will give you the number of bytes that have been written.

FileWrite BufferedWriter and PrintWriter combined

Ok so I am learning about I/O, and I found the following code in one of the slides. can someone please explain why there is a need to have a FileWrite, BufferedWriter and PrintWriter? I know BufferedWriter is to buffer the output and put it all at once but why would they use FileWriter and PrintWriter ? dont they pretty much do the same with a bit of difference in error handling etc?
And also why do they pass bw to PrintWriter?
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter outFile = new PrintWriter (bw);
Presumably they're using a FileWriter because they want to write to a file. Both BufferedWriter and PrintWriter have to be given another writer to write to - you need some eventual destination.
(Personally I don't like FileWriter as it doesn't let you specify the encoding. I prefer to use FileOutputStream wrapped in an OutputStreamWriter, but that's a different matter.)
BufferedWriter is used for buffering, as you say - although it doesn't buffer all the output, just a fixed amount of it (the size of the buffer). It creates "chunkier" writes to the underlying writer.
As for the use of PrintWriter - well, that exposes some extra methods such as println. Personally I dislike it as it swallows exceptions (you have to check explicitly with checkError, which still doesn't give the details and which I don't think I've ever seen used), but again it depends on what you're doing. The PrintWriter is passed the BufferedWriter as its destination.
So the code below the section you've shown will presumably write to the PrintWriter, which will write to the BufferedWriter, which will (when its buffer is full, or it's flushed or closed) write to the FileWriter, which will in turn convert the character data into bytes on disk.
From the Docs:
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. For example,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
You can understand from this that a BufferedWriter is an efficient way to write stuff.
Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
A FileWriter object is passed to the BufferedWriter as the intent here is to write to some output file using a BufferedWriter.
And finally, a PrintWriter is used for print* methods like println().
PrintWriter from here
Prints formatted representations of objects to a text-output stream.
This class implements all of the print methods found in PrintStream.
It does not contain methods for writing raw bytes, for which a program
should use unencoded byte streams.
from the above statement it seems the main reason to use PrintWriter is to get the access of all the methods of PrintStream like println(),println(char [] x) etc.
BufferedWriter, You are right It's one of the best way to write to a file because it will buffered the character into the virtual memory before writing to a file directly and came up with a newLine() method.
FileWriter from here
FileWriter is meant for writing streams of characters. For writing
streams of raw bytes, consider using a FileOutputStream
.
FileWriter is simply to write plain text(without formatting) it doesn't use any buffer mechanism, whatever comes its way it just writes.
BufferedWriter is a wrapper for Writer classes to allow it to be able to use buffer functionality (to optimize IO).
PrintWriter prints formatted text, you can provide format string along with the data to be printed, though it can directly work with any Writer/OutputStream, just to provide buffering, Writer/OutputStream is 1st passed to BufferedWriter then to have formatted text is passed to PrintWriter
Usually, this kind of Writer chaining is about abstraction. PrintWriter have some useful print and println methods that can be convenient if you want to print Strings and lines to a File. Working directly with FileWriter, you would have to use a more "low level" API. And as you say BufferedWriter is about buffering. So it's basically a matter of what you want to output to the file, and what level of abstraction you prefer.
The objects are wrapped in this order because you want to use the outermost PrintWriter for its more sophisticated formatting. BufferedWriter must be wrapped on something. So FileWriter, as a result, is what BufferedWriter wraps and is the innermost object.

I'm using a program to analyse my Java code and I don't understand the error or how to fix it

I'm using the FindBug program from Maryland University and it gives me this error.
I've tested my code on numerous platforms and it works, so why is this code bad-practice, and what can I do to improve it?
It's telling you the encoding (how the string is turned into bytes) isn't specified.
If you write a text file in Turkey, and load it up in Uzbekistan then you might get different results. Instead (for example) you could specify the encoding directly by converting the string to bytes yourself using a specified encoding (see String.getBytes for an example).
you need to specify the charset
you can use anOutputStreamWriter
fileWriter = new OutputStreamWriter(new FileOutputStream(file),charset);
See the FileWriter documentation: "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."
It can be considered bad practice to depend on default character encoding.
Use FileOutputStream, instead of FileWriter. Which can be wrapped using the OutputStreamWriter, which allows you to pass an encoding in the constructor.
Or else, as said by Jeff, the data won't load correctly.
Example
OutputStream fout = new FileOutputStream("test.txt");
OutputStream bout = new BufferedOutputStream(fout);
OutputStreamWriter out = new OutputStreamWriter(bout, "UTF-8");

Difference between java.io.PrintWriter and java.io.BufferedWriter?

Please look through code below:
// A.class
File file = new File("blah.txt");
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);
// B.class
File file = new File("blah.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bWriter = new BufferedWriter(fileWriter);
What is the difference between these two methods?
When should we use PrintWriter over BufferedWriter?
PrintWriter gives more methods (println), but the most important (and worrying) difference to be aware of is that it swallows exceptions.
You can call checkError later on to see whether any errors have occurred, but typically you'd use PrintWriter for things like writing to the console - or in "quick 'n dirty" apps where you don't want to be bothered by exceptions (and where long-term reliability isn't an issue).
I'm not sure why the "extra formatting abilities" and "don't swallow exceptions" aspects are bundled into the same class - formatting is obviously useful in many places where you don't want exceptions to be swallowed. It would be nice to see BufferedWriter get the same abilities at some point...
The API reference for BufferedWriter and PrintWriter detail the differences.
The main reason to use the PrintWriter is to get access to the printXXX methods like println(). You can essentially use a PrintWriter to write to a file just like you would use System.out to write to the console.
A BufferedWriter is an efficient way to write to a file (or anything else), as it will buffer the characters in Java memory before (probably, depending on the implementation) dropping to C to do the writing to the file.
There is no such concept as a "PrintReader"; the closest you will get is probably java.util.Scanner.
As said in TofuBeer's answer both have their specialties. To take the full advantage of PrintWriter (or any other writer) but also use buffered writing you can wrap the BufferedWriter with the needed one like this:
PrintWriter writer = new PrintWriter(
new BufferedWriter (
new FileWriter("somFile.txt")));
PrintWriter just exposes the print methods on any Writer in character mode.
BufferedWriter is more efficient than , according to its buffered methods.
And it comes with a newLine() method, depending of your system platform, to manipulate text files correctly.
The BufferedReader permits to read a text from file, with bytes converted in characters. It allows to read line by line.
There is no PrintReader, you have to choose another Reader implementation according to the format of your input.
PrintWriter is the most enhanced Writer to write Character data to a file.
The main advantage of PrintWriter over FileWriter and BufferedWriter is:
PrintWriter can communicate directly with the file, and can communicate via some Writer object also.
PrintWriter printwriter = new PrintWriter("blah.txt");
(or)
FileWriter filewriter = new FileWriter("blah.txt");
PrintWriter printwiter = new PrintWriter(filewriter);
We can write any type of Primitive data directly to the file (because we have additional overloaded versions of PrintWriter methods i.e., print() and println()).
printwriter.print(65); //65
bufferedwriter.write(65); //A
printwriter.println(true); //true
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. For example,
Note: Text content in the code blocks is automatically word-wrapped
PrintWriter out =
new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
BufferedWriter - Writes text to an output character stream, buffering characters from a character stream.
PrintWriter - Prints formatted representations of objects to a text output stream.
I think that the reason behind using PrintWriter is already mentioned above but one of the important reason is you an pass a file object directly to the PrintWriter constructor which makes it easy to use it.
File file=new File(“newfile.txt”);
PrintWriter pw=new PrintWriter(file);

Categories