Character Stream

3 0 0
                                    

Difference between character stream and byte stream

1. Byte stream uses FileInputStream and FileOutputStream while character uses FileReader and FileWriter.

2. Byte stream uses CopyBytes class while character uses CopyCharacters class. Both of these classes uses an int to read and write from the file. The only difference is CopyBytes has 8 bits while CopyCharacters has 16 bits.

3. Byte stream descended from InputStream and OutputStream while character stream descended from Reader and Writer.

4. The byte stream handles the input and output that is on integer while the character stream acts as wrapper to convert the integer to character.

===============

class CharacterStreamPractice{

     public static void main(String[] args) throws IOException{

          String yourFileName = "YourFileName.txt";

          CharacterStreamPractice.writeSomething(yourFileName);

          CharacterStreamPractice.writeSomething(yourFileName);

     }

     private static void writeSomething(String fileName) throws IOException{

          try(FileWriter fileWriter = new FileWriter(fileName);

                 Scanner scanner = new Scanner(System.in)

          ){

              String putItHere = "";

               while(scanner.hasNext()){

                    String message = scanner.next();

                    String addingSpace = message.concat(" ");

                    putItHere = putItHere.concat(addingSpace);

                    if(message.equals("999")){

                         break;

                    }

                }

                fileWriter.write(putItHere);

          }

    }

    private static void readSomething(String fileName) throws IOException{

         try(FileReader fileReader = new FileReader(fileName);

                Scanner scanner = new Scanner(fileReader);

          ){

              String message;

               while(scanner.hasNext()){

                    message = scanner.next();

                    String addingSpace = message.concat(" ");

                    System.out.print(addingSpace);

               }

          }

    }

}

===============

Result:

Hello World

999

Java ProgrammingWhere stories live. Discover now