简体   繁体   中英

Convert character-stream to byte-stream and byte-stream to character-stream

so I have to convert input character stream to output byte stream and input byte stream to character output stream. I tried something like this:

Character stream to byte stream (I have to use here FileReader and FileOutputStream):

import java.io.*;

public class Example
{
    public static void main( String[ ] args ) throws IOException 
    {
        FileReader in = new FileReader( "input.txt" );
        FileOutputStream out = new FileOutputStream( "test.txt" );
        int c;

        while ((c = in.read()) != -1)
        {
           out.write(c);
        }

        in.close();
        out.close();
    }
}

Byte stream to character stream (I have to use here FileInputStream and FileWriter):

import java.io.*;

public class Example
{
    public static void main( String[ ] args ) throws IOException 
    {
        FileInputStream in = new FileInputStream( "input.txt" );
        FileWriter out = new FileWriter( "test.txt" );
        int c;

        while ((c = in.read()) != -1)
        {
           out.write(c);
        }

        in.close();
        out.close();
    }
}

It's ok or I have something wrong?

1.You have to use OutputStreamWriter class for converting Character stream to Byte stream. 2.InputStreamReader class for converting Byte stream to Character stream, as these classes are used for stream conversions between two different streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM