Text Size
Saturday, May 21, 2022

Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/cmwhittington/theteach.ca/components/com_komento/helpers/string.php on line 327

Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/cmwhittington/theteach.ca/components/com_komento/helpers/string.php on line 329

Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/cmwhittington/theteach.ca/components/com_komento/helpers/string.php on line 330

Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/cmwhittington/theteach.ca/components/com_komento/helpers/string.php on line 331

Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/cmwhittington/theteach.ca/libraries/gantry/core/utilities/registry/format/ini.php on line 107

Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/cmwhittington/theteach.ca/libraries/gantry/core/utilities/registry/format/ini.php on line 120

Content

Java File IO

Reading and Writing to a text file is an important skill in computer programming. Once you have learned to read and write to the console reading and writing to a file is reletively simple in Java.

Reading from a text file.
FileReader fr = new FileReader("FileName.txt");
BufferedReader br = new BufferedReader (fr);
String input;
input = br.readLine();
br.close();

The first line creates a File Reader that points to the text file FileName.txt this can be any file in the same directory or any file that is deeper in the directory structure. The Buffered Reader uses the File Reader to read a buffered stream of data. The line br.readLine() now reads from the file FileName.txt into the String input. The line br.close() closes the file.

Writing to a text file.
FileWriter fw = new FileWriter ("FileName.txt");
BufferedWriter bw = new BufferedWriter (fw);
bw.write ("Hello", 0, 5);

bw.close();

The only major difference between reading and writing is that the write method for the buffered writer allows more than simply a string to be written.
bw.write("String", Starting Position to write, Number of characters to write);

Leave your comments

0
terms and condition.
  • No comments found
Parent Category: ICS4U