I'm really getting confused by how many different ways there is to write data to a file just with System.IO.
I mean, between FileStream
, StreamWriter
or just the System.IO.file methods... Which one is the best to use?
It even gets more confusing when you see you can use different constructs with any of them, like using using
or not.
Is there any difference between them? Online tutorials seems to only stick to one of them and completely ignores the other ones. Some of these tutorials are even using different ways of referencing the file to write in (using the File
type in some cases, FileInfo
types in others, or even just a string for its path/name).
Any of them is more efficient than the other?
Method 1: Using writeString() method The first two parameters are mandatory for this method to write into a file. It writes the characters as the content of the file. It returns the file path and can throw four types of exceptions. It is better to use when the content of the file is short.
putc() - writes a character to a file. fscanf() - reads a set of data from a file. fprintf() - writes a set of data to a file.
FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
When referring to data or a storage device, writing is taking information and moving it to an alternate location. For example, saving data onto a diskette is the same as writing information to a diskette. Almost all forms of media are writable, which means any information can be written to it.
Stream
is an abstraction for "bytes of data" that works with things other than files, like bytes sent over a network.
TextReader
s and TextWriter
s are meant for working with text. StreamReader
s and StreamWriter
s are specific kinds which wrap Stream
s.
The File
class is specifically meant to treat a file as a unit entity, not as long stream of bytes. Hence:
Stream
-related classes. It usually makes no sense to keep a 10-MiB byte[]
or string
in memory, unless you really need random access to all of it. File
class to read and write byte[]
s or string
s.There are so many ways because there are many ways to structure data to send. Do you have arrays of strings? Are you streaming data from some other source (like a network stream)? Do you want to write lines of text like a log?
It would help to know what you want to write, then we can help you decide how.
Oh, and always use 'using' if you can. You get resource cleanup even if your code fails which is a good thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With