I am learning about java io concepts and I need to clarify a doubt about it.
I am trying to read a file using a reader like BufferedReader and write the same to OutputStream like BufferedOutputstream. Here is a sample of my code.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
public class ReaderToStream
{
public static void main(String[] args)throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(new File("f1.txt")));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("f2.txt")));
int ch = 0;
while((ch=br.read())!=-1)
{
bos.write(ch);
}
bos.close();
br.close();
}
}
I know that reader reads in characters and the output stream writes in bytes, but how can we handle it perfectly, because when my file has normal English characters, there is no problem, but when I have symbols or other language characters(for example காலை வணக்கம், 早上好) it copies the text to some random text(like æ©ä`好).
can anyone help me to understand the topics clearly in-depth?
Thanks for any help, and sorry if asked anything stupid.
You can use an adapter design pattern implementation called OutputStreamWriter.
Your code snippet using this class, looks like the code below:
Also, u can specify an encoding: