I am working on I/O classes in Java. I understand that there are two important type of streams: byte stream and character stream. But... I have tried to read and write text file with byte stream and it worked. Here is the code:
File klasor = new File("C:\\Java");
if(!klasor.exists()) klasor.mkdirs();
File kaynakDosya = new File("C:\\Java\\kaynak.txt");
if(!kaynakDosya.exists()) kaynakDosya.createNewFile();
File hedefDosya = new File("C:\\Java\\hedef.txt");
if(!hedefDosya.exists()) hedefDosya.createNewFile();
FileInputStream kaynak = new FileInputStream(kaynakDosya);
FileOutputStream hedef = new FileOutputStream(hedefDosya);
int c;
while((c = kaynak.read()) != -1) {
hedef.write(c);
}
if(kaynak != null) {
kaynak.close();
}
if(hedef != null) {
hedef.close();
}
And then I did the same with character stream:
File klasor = new File("C:\\Java");
if(!klasor.exists()) klasor.mkdirs();
File kaynakDosya = new File("C:\\Java\\kaynak.txt");
if(!kaynakDosya.exists()) kaynakDosya.createNewFile();
File hedefDosya = new File("C:\\Java\\hedef.txt");
if(!hedefDosya.exists()) hedefDosya.createNewFile();
FileReader kaynak = new FileReader(kaynakDosya);
FileWriter hedef = new FileWriter(hedefDosya);
int c;
while((c = kaynak.read()) != -1) {
hedef.write(c);
}
if(kaynak != null) {
kaynak.close();
}
if(hedef != null) {
hedef.close();
}
These two produced the same result. So, I want to know, why shouldn't I use byte stream here but character stream? (I have read some articles as well as related questions here on stackoverflow and they say so) I know that character stream will read it character by character, but what advantage does this give me? Or what problems could occur if I read characters using byte stream? I hope my question is clear. I would appreciate real-case examples.