Register   Login   About   Study   Enterprise   Share
AI / Internet Technology University (AITU)
Fast Login - available after registration







|

Top Links: >> 80. Technology >> Internet Technology Summit Program >> 1. Java Introduction
Current Topic: 1.4. Input-Output and Exceptions
Sub-Topics: 1.4.1. IO Utilities | 1.4.2. Handling Exceptions | 1.4.3. Input from Keyboard with Scanner
-- Scroll to check for more content below...
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
Make sure that you understand and completed the previous subject.

Reading and Writing files in Java is accomplished with Input and Output streams, a set of classes collected in the java.io package.
There are two types of files: text files and binary files. Text files, such as HTML files or files with the TXT extension, consist of characters. Usually, people can read text files without any special applications. Text files are handled in Java with Character Streams.

Binary files, such as MS Word files with the DOC or DOCX extension, MS Excel files, PDF files, and many other file formats consist of bytes and usually require special applications, like MS Word, etc. to visualize these files into a readable form. Binary files are handled in Java with Binary Streams.

In a Java program we start reading a file by connecting to a file and creating a powerful stream object for streaming data.


For text files the source might look like this:


String pathToFile = "c:/its-resources/day6.txt";
FileReader fr=new FileReader(pathToFile);
BufferedReader br=new BufferedReader(fr);


We can think about the BufferedReader stream as a smarter wrapper around the simpler FileReader stream.
Using wrappers is a very common thing in programming in general and in Java programming specifically.
Now we have the BufferedReader stream that we called br and can use this object for streaming data.

Why do we talk about streaming data instead of just reading a whole file?

The file can be huge and reading the file by chunks or streaming the file is a more reliable way of reading. Input/Output operations are supported by Operating System (OS) mechanisms, such as OS input and output buffers, which might have their own limitations.

For text files it is natural to read a single line in the loop. The BufferedReader has a convenient method readLine() that does it for us.
The next several lines provide the for loop for reading the pieces of the file, line by line. In the loop we check for the end of the file. When the attempt to read the next portion comes back with null, this means that the file is over and our program will stop reading.


// prepare for the loop
String text = ""; // the String object to collect all lines together
String line = ""; // a single line to be filled by the readLine() method
for(; (line = br.readLine()) !=null; ) {
// collecting all lines together and providing a proper line separator between the lines
// The line separator is defined by the System, which knows the difference between Windows and Linux line breaks
text += line + System.lineSeparator();
}


In the example, we assumed that the file is not very big and can be collected into a single Java String called text. Alternatively, each line could be directed to a network, or to a visualization device.
At the end of reading it is a good idea to close the BufferedReader Input stream.


br.close();


The FileWriter and PrintWriter IO classes is a perfect couple for writing text files. The FileWriter object will create a new text file and the PrintWriter object will write data into the file. Note, that the PrintWriter is a wrapper around the FileWriter stream. The PrintWriter has a very convenient println(String s) method


String pathToFile = "c:/its-resources/day6.txt";
String[] lines = { "This","is","the test"}; // will be written in a file as 3 lines
FileWriter fw = new FileWriter(pathToFile); // this line will be red
// mouse over and read about exception - then click on the suggested link
PrintWriter pw=new PrintWriter (fw);
for(int i=0; i < lines.length; i++){
pw.println(lines[i]);
}
pw.close();





In a similar way, we can read and write binary files. Reading binary files can be accomplished with the FileInputStream and BufferedInputStream classes.


FileInputStream fis=new FileInputStream(pathToBinFile);
BufferedInputStream bis=new BufferedInputStream(fis);


We assume that the file is not very big and will try to allocate array of bytes for reading.


// get a size of the file to read
File file = new File(name);
int size = (int) file.length();
// allocate a byte array for reading assuming it is not a huge file
byte[] bytes = new byte[size];
int numberOfBytesToRead = 4096; // reading by chunks


Our plan is to read from the file by chunks of 4096 bytes at once.
Several lines in the for loop provide reading from the file into the byte array. Each cycle of the loop will fill in another portion of the byte array with the bytes from the file. In the for loop we check if the next chunk can fit into the rest of array. If the numberOfBytesToRead is bigger than the rest of the array, we stop the for loop, calculate a precise number of bytes (moreBytesToRead) and read the rest of bytes into the array. And then we close the stream.
Was it clear so far?



int i=0; // index to start reading from the file into the array of bytes
for(; i < bytes.length; i = i + numberOfBytesToRead) {
bis.read(bytes, i, numberOfBytesToRead); // read numberOfBytesToRead from index i
}
int moreBytesToRead = bytes.length - i;
bis.read(bytes, i, moreBytesToRead); // read the remaining bytes
bis.close();


And writing binary files can be done with the FileOutputStream and BufferedOutputStream classes.


FileOutputStream fos = new FileOutputStream(name); // create a new file
BufferedOutputStream bos=new BufferedOutputStream (fos); // wrap a convenient stream for writing lines
int numberOfBytesToWrite = 4096; // prepare to write by 4096 bytes at once


In the loop we write into the file from the array of bytes. Each time we write the next portion of the byte array. Note, that the program changes the index i, which serves as a cursor pointing to the current place in the array from which we write into the file. Each cycle writes 4096 bytes (numberOfBytesToWrite). There is a condition that checks if the rest of the byte array is bigger than the numberOfBytesToWrite. When this condition is not true, we finish the loop.
Then we calculate a precise number of bytes to write (moreBytesToWrite) and finish writing into the file.


int i=0; // byte index to start writing from the array of bytes
for(; i < bytes.length; i = i + numberOfBytesToWrite) {
bos.write(bytes, i, numberOfBytesToWrite); // write numberOfBytesToWrite from index i
}
int moreBytesToWrite = bytes.length - i;
bos.write(bytes, i, moreBytesToWrite); // write the remaining bytes


After finishing writing, the program does two important things: flush the OS buffers and close the stream.


// flush OS buffers, otherwise OS can wait till the buffers are full before writing to a file
bos.flush();
bos.close(); // and close the stream


Assignments:
1. Open Eclipse and create a new Java project week2. Under the src folder create a new package day6.
Under the package day6 create a new class IOWriteText and create the main method there.

In the main method type the lines to write a text file from the section related to writing text files.
public static void main(String[] args) {
// type the lines to write a text file from the section related to writing text
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

2. Under the package day6 create a new class IOReadText and create the main method there.
In the main method type the lines to write a text file from the section related to reading text files.
public static void main(String[] args) {
// type the lines to read a text file from the section related to reading text
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

3. Under the package day6 create a new class IOWriteBin and create the main method there.
In the main method type the lines to write a text file from the section related to writing binary files.
public static void main(String[] args) {
// type the lines to write a text file from the section related to writing binary
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

4. Under the package day6 create a new class IOReadBin and create the main method there.
In the main method type the lines to read a text file from the section related to reading binary files.

public static void main(String[] args) {
// type the lines to read a text file from the section related to reading binary
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

5. Recommended reading and watching:
https://www.tutorialspoint. com/java/java_files_io.htm
https://www.youtube.com/watch?v=_jhCvy8_lGE

https://www.utc.edu/center-information-security-assurance/docs/1110-chapter11-input-output.pptx

http://www.hciegypt.com/ayman/Files/Pl2/Pl2_Ch4.pdf

Search Google and Youtube for even better presentations on this subject, read, watch, select and email 2 best links to dean@ituniversity.us
| Check Your Progress | Propose QnA | Have a question or comments for open discussion?
<br/>      String pathToFile = "c:/its-resources/day6.txt";
<br/>      FileReader fr=new FileReader(pathToFile);
<br/>      BufferedReader br=new BufferedReader(fr);
<br/>


We can think about the BufferedReader stream as a smarter wrapper around the simpler FileReader stream.
Using wrappers is a very common thing in programming in general and in Java programming specifically.
Now we have the BufferedReader stream that we called br and can use this object for streaming data.

Why do we talk about streaming data instead of just reading a whole file?

The file can be huge and reading the file by chunks or streaming the file is a more reliable way of reading. Input/Output operations are supported by Operating System (OS) mechanisms, such as OS input and output buffers, which might have their own limitations.

For text files it is natural to read a single line in the loop. The BufferedReader has a convenient method readLine() that does it for us.
The next several lines provide the for loop for reading the pieces of the file, line by line. In the loop we check for the end of the file. When the attempt to read the next portion comes back with null, this means that the file is over and our program will stop reading.

<br/>	// prepare for the loop
<br/>	String text = ""; // the String object to collect all lines together
<br/>	String line = ""; // a single line to be filled by the readLine() method
<br/>	for(; (line = br.readLine()) !=null; ) {
<br/>                // collecting all lines together and providing a proper <b>line separator</b> between the lines
<br/>                // The line separator is defined by the System, which knows the difference between Windows and Linux line breaks
<br/>		text += line + System.lineSeparator(); 
<br/>	}  
<br/>


In the example, we assumed that the file is not very big and can be collected into a single Java String called text. Alternatively, each line could be directed to a network, or to a visualization device.
At the end of reading it is a good idea to close the BufferedReader Input stream.

<br/>	br.close();
<br/>


The FileWriter and PrintWriter IO classes is a perfect couple for writing text files. The FileWriter object will create a new text file and the PrintWriter object will write data into the file. Note, that the PrintWriter is a wrapper around the FileWriter stream. The PrintWriter has a very convenient println(String s) method

<br/>        String pathToFile = "c:/its-resources/day6.txt";
<br/>        String[] lines = { "This","is","the test"}; // will be written in a file as 3 lines
<br/>	FileWriter fw = new FileWriter(pathToFile); // this line will be red
<br/>        // mouse over and read about exception - then click on the suggested link
<br/>	PrintWriter pw=new PrintWriter (fw);
<br/>	for(int i=0; i < lines.length; i++){
<br/>		 pw.println(lines[i]);
<br/>	}  	
<br/>	pw.close();
<br/>





In a similar way, we can read and write binary files. Reading binary files can be accomplished with the FileInputStream and BufferedInputStream classes.

<br/>	FileInputStream fis=new FileInputStream(pathToBinFile);
<br/>	BufferedInputStream bis=new BufferedInputStream(fis);
<br/>


We assume that the file is not very big and will try to allocate array of bytes for reading.

<br/>	// get a size of the file to read
<br/>	File file = new File(name);
<br/>        int size = (int) file.length();
<br/>        // allocate a byte array for reading assuming it is not a huge file
<br/>	byte[] bytes = new byte[size]; 
<br/>	int numberOfBytesToRead = 4096; // reading by chunks
<br/>


Our plan is to read from the file by chunks of 4096 bytes at once.
Several lines in the for loop provide reading from the file into the byte array. Each cycle of the loop will fill in another portion of the byte array with the bytes from the file. In the for loop we check if the next chunk can fit into the rest of array. If the numberOfBytesToRead is bigger than the rest of the array, we stop the for loop, calculate a precise number of bytes (moreBytesToRead) and read the rest of bytes into the array. And then we close the stream.





Was it clear so far?



<br/>	int i=0; // index to start reading from the file into the array of bytes
<br/>	for(; i < bytes.length; i = i + numberOfBytesToRead) {
<br/>		bis.read(bytes, i, numberOfBytesToRead); // read numberOfBytesToRead from index i
<br/>	}  	
<br/>	int moreBytesToRead = bytes.length - i;
<br/>	bis.read(bytes, i, moreBytesToRead); // read the remaining bytes
<br/>	bis.close();
<br/>


And writing binary files can be done with the FileOutputStream and BufferedOutputStream classes.

<br/>		FileOutputStream fos = new FileOutputStream(name); // create a new file 
<br/>		BufferedOutputStream bos=new BufferedOutputStream (fos); // wrap a convenient stream for writing lines
<br/>		int numberOfBytesToWrite = 4096; // prepare to write by 4096 bytes at once
<br/>


In the loop we write into the file from the array of bytes. Each time we write the next portion of the byte array. Note, that the program changes the index i, which serves as a cursor pointing to the current place in the array from which we write into the file. Each cycle writes 4096 bytes (numberOfBytesToWrite). There is a condition that checks if the rest of the byte array is bigger than the numberOfBytesToWrite. When this condition is not true, we finish the loop.
Then we calculate a precise number of bytes to write (moreBytesToWrite) and finish writing into the file.

<br/>		int i=0; // byte index to start writing from the array of bytes
<br/>		for(; i < bytes.length; i = i + numberOfBytesToWrite) {
<br/>			 bos.write(bytes, i, numberOfBytesToWrite); // write numberOfBytesToWrite from index i
<br/>		}  	
<br/>		int moreBytesToWrite = bytes.length - i;
<br/>		bos.write(bytes, i, moreBytesToWrite); // write the remaining bytes
<br/>


After finishing writing, the program does two important things: flush the OS buffers and close the stream.

<br/>		// flush OS buffers, otherwise OS can wait till the buffers are full before writing to a file
<br/>		bos.flush(); 
<br/>		bos.close(); // and close the stream
<br/>


Assignments:
1. Open Eclipse and create a new Java project week2. Under the src folder create a new package day6.
Under the package day6 create a new class IOWriteText and create the main method there.

In the main method type the lines to write a text file from the section related to writing text files.
public static void main(String[] args) {
// type the lines to write a text file from the section related to writing text
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

2. Under the package day6 create a new class IOReadText and create the main method there.
In the main method type the lines to write a text file from the section related to reading text files.
public static void main(String[] args) {
// type the lines to read a text file from the section related to reading text
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

3. Under the package day6 create a new class IOWriteBin and create the main method there.
In the main method type the lines to write a text file from the section related to writing binary files.
public static void main(String[] args) {
// type the lines to write a text file from the section related to writing binary
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

4. Under the package day6 create a new class IOReadBin and create the main method there.
In the main method type the lines to read a text file from the section related to reading binary files.

public static void main(String[] args) {
// type the lines to read a text file from the section related to reading binary
}

Then Run this class (Click on the source in Eclipse ? right mouse click ? RUN AS ? Java Application).

5. Recommended reading and watching:
https://www.tutorialspoint. com/java/java_files_io.htm
https://www.youtube.com/watch?v=_jhCvy8_lGE

https://www.utc.edu/center-information-security-assurance/docs/1110-chapter11-input-output.pptx

http://www.hciegypt.com/ayman/Files/Pl2/Pl2_Ch4.pdf

Search Google and Youtube for even better presentations on this subject, read, watch, select and email 2 best links to dean@ituniversity.us

| Check Your Progress | Propose QnA | Have a question or comments for open discussion?

Have a suggestion? - shoot an email
Looking for something special? - Talk to me
Read: IT of the future: AI and Semantic Cloud Architecture | Fixing Education
Do you want to move from theory to practice and become a magician? Learn and work with us at Internet Technology University (ITU) - JavaSchool.com.

Technology that we offer and How this works: English | Spanish | Russian | French

Internet Technology University | JavaSchool.com | Copyrights © Since 1997 | All Rights Reserved
Patents: US10956676, US7032006, US7774751, US7966093, US8051026, US8863234
Including conversational semantic decision support systems (CSDS) and bringing us closer to The message from 2040
Privacy Policy