Arvutiteaduse instituut
  1. Kursused
  2. 2017/18 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (P2NC.01.083)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2017/18 kevad

  • Home
  • Materials
  • Java Glossary
  • Source Example
  • Cheat sheet (S1-S6)
  • Grading
  • Links
Session 10

Class for text encoding

The classes InputStream and OutputStream operate on bytes. If we have to process a text file, it is not efficient to convert the text into bytes and vice versa. Luckily, Java has some extra classes - InputStreamReader and OutputStreamWriter.

InputStreamReader is a bridge between the byte streams and character streams. The class reads bytes and decodes them into characters using a specified charset. An example of character:

//Define input byte stream
InputStream myInput = new FileInputStream("myFile.txt"); 
//Read characters using the byte stream
InputStreamReader myTextIn = new InputStreamReader(myInput, "UTF-8");
myTextIn.read(1024);

OutputStreamWriter is a bridge from character streams to byte streams: characters written to it are encoded into bytes using a specified charset. An example:

//Define output byte stream
OutputStream myCopy = new FileOutputStream("myCopyFile.txt");
//Write characters using the output byte stream
OutputStreamWriter myTextOut = new OutputStreamWriter(myCopy, "UTF-8");
myTextOut.write("hello world!");

Most probably you have notices that the method write of the class OutputStreamWriteri takes in a string; however, InputStreamReader cannot read text line by line. The reason is similar to the input byte stream InputStream: InputStreamReader does not read the whole file at once, but reads it in portions. This is because InputStreamReader has to decode bytes into symbols and put them into the buffer, not to look for a new line break. If we need to read the text line by line, we have to use another classes. Check the next page :)

Session 10
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused