java.io Classes:
There are many Java I/O library classes, so to simplify this (as the textbook does), let's just look at a few IO classes. Be sure to import java.io.*; to use these:
To write text to a file using default character encoding (not discussed in this course), the following is one way to open a text file:
FileOutputStream outFile=null;
try {
outFile =
new FileOutputStream("info.txt");
}catch( FileNotFoundException e ){
System.err.println(e);
return ; // may want to return an error code
} //end catch
PrintWriter prtWriter = new PrintWriter(outFile, true);
To write text to a file using specific character encoding, do the following 3 steps to open the text file:
OutputStreamWriter outStream =
new OutputStreamWriter(outFile, "8859_1");
PrintWriter prtWriter =
new PrintWriter(outStream, true);
import java.io.*;
public class TryOutputTextFile{
public static void main( String [] args ){
FileOutputStream outFile=null;
try {
outFile =
new FileOutputStream("info.txt");
}catch( FileNotFoundException e ){
System.err.println(e);
return ;
} //end catch
PrintWriter prtWriter =
new PrintWriter(outFile, true);
prtWriter.println("Writing a String");
prtWriter.println(Math.PI);
prtWriter.println(true);
} // end main
} // end class TryOutputTextFile
(use File and PrintWriter in java.io.*)
File file = new File("myFile.txt");
PrintWriter outfile = new PrintWriter(file);
// now you can call print and println and printf? on outfile
Exercise 11.1
/* Exercise 11.1
Change any of the previous Java programs written that wrote to System.out to write to a text file. */
import java.io.*;
public class Exercise_11_1_WriteTextFile
{
public static void main(String[] args)
{
// Method 1
FileOutputStream oOutFile1 = null;
System.out.println("Write to file");
try
{
oOutFile1 = new FileOutputStream("SampleOutput1.txt");
}
catch(FileNotFoundException e)
{
System.err.println("Error: " + e);
return;
}
PrintWriter oPrintWriter1 = new PrintWriter(oOutFile1, true);
// Write to File
oPrintWriter1.println("A Java method is called what in C/C++? --> Functions");
oPrintWriter1.println("Java is compiled into --> intermediate byte code which is stored in a file with .class extension.");
oPrintWriter1.println("The Java interpreter is called the --> Java Virtual Machine");
System.out.println("End write to file");
// Method 2
// File oOutFile2 = new File("SampleOutput2.txt");
// PrintWriter oPrintStream2 = new PrintWriter(oOutFile2);
// Note: still need try catch OR give compile error
// oPrintStream2.println("Hello");
}
}
java.io.File file=
new java.io.File("input.txt");
Scanner scanner = new Scanner(file);
now you may use the scanner methods that you have been with System.in. To check for end of file, you may use thehasNext() Scanner method.
FileInputStream inFile = null;
try {
infile = new FileInputStream("info.txt");
}catch( FileNotFoundException e ){
System.err.println(e);
return ;
} // end catch
InputStreamReader inStrRdr =
new InputStreamReader(inFile, "8859_1");
BufferedReader reader = new BufferedReader(inStrRdr);
Example of opening with special character encoding (using "info.txt" file already created):
import java.io.*;
public class TryInputTextFile{
public static void main( String [] args ){
String str="";
double dnum=0.;
boolean bool=false;
FileInputStream inFile = null;
try {
inFile = new FileInputStream("info.txt");
}
catch( FileNotFoundException e ){
System.err.println(e);
return ;
} // end catch
InputStreamReader inStrRdr=
new InputStreamReader(inFile, "8859_1");
BufferedReader reader = new BufferedReader(inStrRdr);
try {
str = reader.readLine();
dnum = Double.parseDouble(reader.readLine());
bool = reader.readLine().equals("true") ;
}
catch( IOException ie ){
System.err.println("Error in input: " + ie);
}
catch(NumberFormatException ne){
System.err.println("Error in input: " + ne);
}
System.out.println(str);
System.out.println(dnum);
System.out.println(bool);
} // end main
} // end class TryInputTextFile
Exercise 11.2
/*
Exercise 11.2 Change any of the previous Java programs you wrote that read from System.in to read from a text file
(create the file first).
*/
import java.io.*;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Exercise_11_2_ReadTextFile
{
public static void main(String[] args)
{
FileOutputStream oOutputFile = null;
FileInputStream oInputFile = null;
try
{
oOutputFile = new FileOutputStream("SystemInput.txt");
oInputFile = new FileInputStream("SystemInput.txt");
}
catch(FileNotFoundException e)
{
System.err.println("Error: " + e);
}
PrintWriter oPrintWriter = new PrintWriter(oOutputFile, true);
oPrintWriter.println(10);
oPrintWriter.println(20);
// Method 1: Using default Encoding
Scanner oScanner = new Scanner(oInputFile);
int result = 0;
try
{
int i = oScanner.nextInt();
int j = oScanner.nextInt();
result = i * j;
}
catch(InputMismatchException e) // try to read file with one number as 10.12
{
System.err.println("InputMismatchException: " + e);
}
catch(NoSuchElementException e) // try to read file having only one number
{
System.err.println("NoSuchElementException: " + e);
}
System.out.println("Result: " + result);
/*
// Method 2
InputStreamReader oInputStreamReader = new InputStreamReader(oInputFile);//, "8859_1"); // Encoding argument gives compile error
BufferedReader oReader = new BufferedReader(oInputStreamReader);
String s_EachLine = "";
int result = 0;
try
{
s_EachLine = oReader.readLine();
int i = Integer.parseInt(s_EachLine);
s_EachLine = oReader.readLine(); // To Do: Check EOF every time when read from file
int j = Integer.parseInt(s_EachLine);
result = i * j;
}
catch (IOException e)
{
System.err.println("IO Exception: " + e);
}
catch(NumberFormatException e)
{
System.out.println("Number Format Exception: " + e);
}
System.out.println("Result: " + result);
*/
}
}
/*
// Example program given in class material
import java.io.*;
public class Exercise_11_2_ReadTextFile{
public static void main( String [] args ){
String str="";
double dnum=0.;
boolean bool=false;
FileInputStream inFile = null;
try {
inFile = new FileInputStream("info.txt");
}
catch( FileNotFoundException e ){
System.err.println(e);
return ;
} // end catch
InputStreamReader inStrRdr=
new InputStreamReader(inFile, "8859_1");
BufferedReader reader = new BufferedReader(inStrRdr);
try {
str = reader.readLine();
dnum = Double.parseDouble(reader.readLine());
bool = reader.readLine().equals("true") ;
}
catch( IOException ie ){
System.err.println("Error in input: " + ie);
}
catch(NumberFormatException ne){
System.err.println("Error in input: " + ne);
}
System.out.println(str);
System.out.println(dnum);
System.out.println(bool);
} // end main
} // end class TryInputTextFile
*/