You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
Creating IO Utilities Reading and writing files is a very common operation that can be used by many applications. This is a good reason to make these operations convenient utilities.
The main methods are not really reusable. They are usually starting points of applications or can be used to test class methods until we move to JUnit library that makes testing easier.
Let us create reusable IO Utilities that we can use in the future within our Java applications. Think of this exercise as your first attempt in creating your own library.
A complete source is provided below. There are two methods for text and two for binary files and the main method is testing all four methods.
We plan to use these methods as utilities for reading and writing, so we make the methods static.
Any program can call static methods directly without creating an object.
For example: String text = IOMaster.readTextFile("c:/its-resources/day6.txt");
package day7;
import java.io.*;
/**
* Write array of string into the file Then read this file and print the lines
*
* @author Jeff.Zhuk@JavaSchool.com
*
*/
public class IOMaster {
/**
* The writeTextFile() method creates a new file and writes a set of lines
* to the file
*
* @param name
* @param lines
* @throws IOException
*/
public static void writeTextFile(String name, String[] lines)
throws IOException {
FileWriter fw = new FileWriter(name); // create a new file
PrintWriter pw = new PrintWriter(fw); // get a stream for writing lines
for (int i = 0; i < lines.length; i++) {
pw.println(lines[i]); // write line by line into the file
}
// flush OS buffers, otherwise OS can wait till the buffers are full
// before writing to a file
pw.flush();
// do not forget to close!
pw.close();
}
/**
* The readTextFile() method connects to an existing file and reads from the
* file
*
* @param name
* @return text
* @throws IOException
*/
public static String readTextFile(String name) throws IOException {
FileReader fr = new FileReader(name);
BufferedReader br = new BufferedReader(fr);
// prepare for the loop
String text = ""; // the String object to collect the file
String line = ""; // a single line to be filled by the readLine() method
for (; (line = br.readLine()) != null;) {
text += line + System.lineSeparator(); // collecting all lines
}
br.close();
return text;
}
/**
* The writeBinFile() method creates a new file and writes a set of lines to
* the file
*
* @param name
* @param bytes
* @throws IOException
*/
public static void writeBinFile(String name, byte[] bytes)
throws IOException {
FileOutputStream fos = new FileOutputStream(name); // create a new file
// get a stream to write bytes
BufferedOutputStream bos = new BufferedOutputStream(fos);
int numberOfBytesToWrite = 4096; // a standard block to write
int totalBytesToWrite = bytes.length;
int i = 0; // byte index to start writing from the array of bytes
for (; i < totalBytesToWrite; i = i + numberOfBytesToWrite) {
int numberOfBytesLeft = totalBytesToWrite - i;
if (numberOfBytesLeft < numberOfBytesToWrite) {
numberOfBytesToWrite = numberOfBytesLeft;
}
// writing bytes starting from index i
bos.write(bytes, i, numberOfBytesToWrite);
}
// flush OS buffers, otherwise OS can wait till the buffers are full
bos.flush();
bos.close(); // and close the stream
}
/**
* The readBinFile() method connects to an existing file and reads from the
* file
*
* @param name
* @return bytes
* @throws IOException
*/
public static byte[] readBinFile(String name) throws IOException {
FileInputStream fis = new FileInputStream(name);
BufferedInputStream bis = new BufferedInputStream(fis);
// 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 standard blocks
int i = 0; // byte index to start reading from the file into the array
for (; i < bytes.length; i = i + numberOfBytesToRead) {
int numberOfBytesLeft = size - i;
if (numberOfBytesLeft < numberOfBytesToRead) {
numberOfBytesToRead = numberOfBytesLeft;
}
bis.read(bytes, i, numberOfBytesToRead); // read from index i
}
bis.close();
return bytes;
}
/**
* Test all methods in the main method
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
testTextMethods();
testBinMethods();
}
public static void testTextMethods() throws IOException {
String[] lines = { "Jeff", "Alicia", "Karen" };
String name = "c:/its-resources/day6.txt";
// test writing text file
IOMaster.writeTextFile(name, lines);
// test reading text file
String text = IOMaster.readTextFile(name);
System.out.println(text); // display the file content
// Check with Windows Explorer and open to the file
}
public static void testBinMethods() throws IOException {
byte[] data = { 1, 2, 3, 4, 5, 6 };
String name = "c:/its-resources/day6.bin";
// test writing text file
IOMaster.writeBinFile(name, data);
// test reading text file
byte[] bytes = IOMaster.readBinFile(name);
System.out.println("Number of bytes: " + bytes.length);
// Check with Windows Explorer if the file was written
}
}
Was it clear so far?
Assignments: 1. Open Eclipse and navigate to the Java project week2. Under the src folder create a new package day7.
Under the package day7 create a new class IOMaster and type the source above into the class. (Do not copy/paste, just type.)
When finished, run the main method: Right mouse click on the source – Run As – Java Application.
Check the results in the console.
2. Open Windows Explorer and navigate to the folder c:/its-resources. Create in this folder a new text file and type in this file the days of the week. Save this file as day7.txt.
3. Open Eclipse and navigate to the Java project week2 in the package day7 create another new class TestReadText.
In this class create the main method and in the main method call the utility IOMaster.readTextFile with the argument "c:/its-resources/day7.txt".
The utility will return the text that you typed in this file manually.
Your line in the main method will look like this:
String text = IOMaster.readTextFile("c:/its-resources/day7.txt");
Then add the line to display the text.
When finished, run the main method: Right mouse click on the source – Run As – Java Application.
Check the results in the console.
4. In a similar way create and run the following classes: TestWriteText, TestWriteBin, and TestReadBin
<br/>package day7;
<br/>
<br/>import java.io.*;
<br/>
<br/>/**
<br/> * Write array of string into the file Then read this file and print the lines
<br/> *
<br/> * @author Jeff.Zhuk@JavaSchool.com
<br/> *
<br/> */
<br/>public class IOMaster {
<br/> /**
<br/> * The writeTextFile() method creates a new file and writes a set of lines
<br/> * to the file
<br/> *
<br/> * @param name
<br/> * @param lines
<br/> * @throws IOException
<br/> */
<br/> public static void writeTextFile(String name, String[] lines)
<br/> throws IOException {
<br/> FileWriter fw = new FileWriter(name); // create a new file
<br/> PrintWriter pw = new PrintWriter(fw); // get a stream for writing lines
<br/> for (int i = 0; i < lines.length; i++) {
<br/> pw.println(lines[i]); // write line by line into the file
<br/> }
<br/> // flush OS buffers, otherwise OS can wait till the buffers are full
<br/> // before writing to a file
<br/> pw.flush();
<br/> // do not forget to close!
<br/> pw.close();
<br/> }
<br/>
<br/> /**
<br/> * The readTextFile() method connects to an existing file and reads from the
<br/> * file
<br/> *
<br/> * @param name
<br/> * @return text
<br/> * @throws IOException
<br/> */
<br/> public static String readTextFile(String name) throws IOException {
<br/> FileReader fr = new FileReader(name);
<br/> BufferedReader br = new BufferedReader(fr);
<br/> // prepare for the loop
<br/> String text = ""; // the String object to collect the file
<br/> String line = ""; // a single line to be filled by the readLine() method
<br/> for (; (line = br.readLine()) != null;) {
<br/> text += line + System.lineSeparator(); // collecting all lines
<br/> }
<br/> br.close();
<br/> return text;
<br/> }
<br/>
<br/> /**
<br/> * The writeBinFile() method creates a new file and writes a set of lines to
<br/> * the file
<br/> *
<br/> * @param name
<br/> * @param bytes
<br/> * @throws IOException
<br/> */
<br/> public static void writeBinFile(String name, byte[] bytes)
<br/> throws IOException {
<br/> FileOutputStream fos = new FileOutputStream(name); // create a new file
<br/> // get a stream to write bytes
<br/> BufferedOutputStream bos = new BufferedOutputStream(fos);
<br/> int numberOfBytesToWrite = 4096; // a standard block to write
<br/> int totalBytesToWrite = bytes.length;
<br/> int i = 0; // byte index to start writing from the array of bytes
<br/> for (; i < totalBytesToWrite; i = i + numberOfBytesToWrite) {
<br/> int numberOfBytesLeft = totalBytesToWrite - i;
<br/> if (numberOfBytesLeft < numberOfBytesToWrite) {
<br/> numberOfBytesToWrite = numberOfBytesLeft;
<br/> }
<br/> // writing bytes starting from index i
<br/> bos.write(bytes, i, numberOfBytesToWrite);
<br/> }
<br/> // flush OS buffers, otherwise OS can wait till the buffers are full
<br/> bos.flush();
<br/> bos.close(); // and close the stream
<br/> }
<br/>
<br/> /**
<br/> * The readBinFile() method connects to an existing file and reads from the
<br/> * file
<br/> *
<br/> * @param name
<br/> * @return bytes
<br/> * @throws IOException
<br/> */
<br/> public static byte[] readBinFile(String name) throws IOException {
<br/> FileInputStream fis = new FileInputStream(name);
<br/> BufferedInputStream bis = new BufferedInputStream(fis);
<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 standard blocks
<br/> int i = 0; // byte index to start reading from the file into the array
<br/> for (; i < bytes.length; i = i + numberOfBytesToRead) {
<br/> int numberOfBytesLeft = size - i;
<br/> if (numberOfBytesLeft < numberOfBytesToRead) {
<br/> numberOfBytesToRead = numberOfBytesLeft;
<br/> }
<br/> bis.read(bytes, i, numberOfBytesToRead); // read from index i
<br/> }
<br/> bis.close();
<br/> return bytes;
<br/> }
<br/>
<br/> /**
<br/> * Test all methods in the main method
<br/> *
<br/> * @param args
<br/> * @throws IOException
<br/> */
<br/> public static void main(String[] args) throws IOException {
<br/> testTextMethods();
<br/> testBinMethods();
<br/> }
<br/>
<br/> public static void testTextMethods() throws IOException {
<br/> String[] lines = { "Jeff", "Alicia", "Karen" };
<br/> String name = "c:/its-resources/day6.txt";
<br/> // test writing text file
<br/> IOMaster.writeTextFile(name, lines);
<br/> // test reading text file
<br/> String text = IOMaster.readTextFile(name);
<br/> System.out.println(text); // display the file content
<br/> // Check with Windows Explorer and open to the file
<br/> }
<br/>
<br/> public static void testBinMethods() throws IOException {
<br/> byte[] data = { 1, 2, 3, 4, 5, 6 };
<br/> String name = "c:/its-resources/day6.bin";
<br/> // test writing text file
<br/> IOMaster.writeBinFile(name, data);
<br/> // test reading text file
<br/> byte[] bytes = IOMaster.readBinFile(name);
<br/> System.out.println("Number of bytes: " + bytes.length);
<br/> // Check with Windows Explorer if the file was written
<br/> }
<br/>}
<br/>
Was it clear so far?
onclick="window.location.href='/BASE/jsp/demo.jsp?checkFlavor=itsp&issueID=26&intro=general&group=aitu&ur=f'">
Assignments: 1. Open Eclipse and navigate to the Java project week2. Under the src folder create a new package day7.
Under the package day7 create a new class IOMaster and type the source above into the class. (Do not copy/paste, just type.)
When finished, run the main method: Right mouse click on the source – Run As – Java Application.
Check the results in the console.
2. Open Windows Explorer and navigate to the folder c:/its-resources. Create in this folder a new text file and type in this file the days of the week. Save this file as day7.txt.
3. Open Eclipse and navigate to the Java project week2 in the package day7 create another new class TestReadText.
In this class create the main method and in the main method call the utility IOMaster.readTextFile with the argument "c:/its-resources/day7.txt".
The utility will return the text that you typed in this file manually.
Your line in the main method will look like this:
String text = IOMaster.readTextFile("c:/its-resources/day7.txt");
Then add the line to display the text.
When finished, run the main method: Right mouse click on the source – Run As – Java Application.
Check the results in the console.
4. In a similar way create and run the following classes: TestWriteText, TestWriteBin, and TestReadBin