0% found this document useful (0 votes)
18 views16 pages

Lab-Chapter 2 Exception H and File

The document discusses exception handling and file streams in Java. It includes code examples of try/catch blocks to handle exceptions, reading and writing to text and binary files, and file operations like creating and checking files. The examples cover basic concepts of exception handling and different ways of working with files in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views16 pages

Lab-Chapter 2 Exception H and File

The document discusses exception handling and file streams in Java. It includes code examples of try/catch blocks to handle exceptions, reading and writing to text and binary files, and file operations like creating and checking files. The examples cover basic concepts of exception handling and different ways of working with files in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 2 Exception Handling & File Streams Page |1

package exception;

public class Example01


{
public static void main(String[] args)
{
// declare a string with nothing inside
String text = null;
//you will see this at the console
System.out.println("Go Java Go!");
//null'ed strings should crash your program
System.out.println(text.length());

//you will never see this print


System.out.println("done");
}
}

package exception;

public class Example02


{
public static void main(String[] args)
{
String text = null;
//you will see this at the console

System.out.println("Go Java Go!");


Chapter 2 Exception Handling & File Streams Page |2

try
{
//null'ed strings should crash your program
System.out.println(text.length());
}
catch (NullPointerException ex)
{
System.out.println("Exception: cannot get the text's
length");
}
// you will now see this print
System.out.println("done");
}
}
package exception;
import java.util.Scanner;
public class Exception04
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
try
{
System.out.println("Enter number of donuts:");
int donutCount = keyboard.nextInt();
System.out.println("Enter number of glasses of milk:");
int milkCount = keyboard.nextInt();
if (milkCount < 1)
Chapter 2 Exception Handling & File Streams Page |3

throw new Exception("Exception: No milk!");


double donutsPerGlass = donutCount / (double)milkCount;
System.out.println(donutCount + " donuts.");
System.out.println(milkCount + " glasses of milk.");
System.out.println("You have " + donutsPerGlass + " donuts
for each glass of milk.");
}
catch(ArithmeticException aE)
{
System.out.println(aE.getMessage());
System.out.println("Go buy some milk 1.");
}
catch(NumberFormatException nfE)
{
System.out.println(nfE.getMessage());
System.out.println("Go buy some milk 2.");
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.out.println("Go buy some milk 3.");
}

System.out.println("End of program.");
}
}
package filestream;
Chapter 2 Exception Handling & File Streams Page |4

import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileOutputDemo
{
public static void main(String[] args)
{
String fileName = "out.txt";
PrintWriter outputStream = null;
File file1 = null;
try
{
file1 = new File("out.txt");
outputStream = new PrintWriter(file1);
}
catch(FileNotFoundException fnfE)
{
System.out.println("Error opening the file" +fileName);
System.exit(0);

}
System.out.println("Enter three lines of text:");
Scanner keyboard = new Scanner(System.in);

for(int count = 1; count <= 3; count++)


{
String line = keyboard.nextLine();
Chapter 2 Exception Handling & File Streams Page |5

outputStream.println(count + " " + line);


}

outputStream.close();
System.out.println("Those lines were written to "
+file1.getAbsolutePath());
}
}
package filestream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class AppendTextFile
{
public static void main(String[] args)
{
String fileName = "out.txt";
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new
FileOutputStream(fileName,true));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file" +fileName);
System.exit(0);
}
Chapter 2 Exception Handling & File Streams Page |6

System.out.println("Enter three lines of text:");


Scanner keyboard = new Scanner(System.in);
for(int count = 1; count <= 3; count++)
{
String line = keyboard.nextLine();
outputStream.println(count + " " + line);
}
outputStream.close();
System.out.println("Those lines were written to " +fileName);
}

package filestream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileInputStream;
public class TextFileInputDemo
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println(" Please Enter a file name to be read");
String fileName = input.next();
Scanner inputStream = null;

System.out.println("The file " + fileName + "\n contains the


following lines:\n");
Chapter 2 Exception Handling & File Streams Page |7

try
{
inputStream = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
System.exit(0);
}

while(inputStream.hasNextLine())
{
String line = inputStream.nextLine();
System.out.println(line);
}
inputStream.close();
}
}

package filestream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class BinaryOutputDemo


Chapter 2 Exception Handling & File Streams Page |8

{
public static void main(String[] args)
{
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream = new
ObjectOutputStream(new FileOutputStream(fileName));
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter nonnegative integers.");
System.out.println("Place a negative number at the "+
"end.");
int anInteger;
do
{
anInteger = keyboard.nextInt();
outputStream.writeInt(anInteger);
} while (anInteger >= 0);

System.out.println("Numbers and sentinel value");


System.out.println("written to the file " + fileName);
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening the file " +
fileName);
}
catch(IOException e)
Chapter 2 Exception Handling & File Streams Page |9

{
System.out.println("Problem with output to file " +
fileName);
}
}
}

package filestream;

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class BinaryInputDemo
{
public static void main(String[] args)
{
String fileName = "numbers.dat";
try
{
ObjectInputStream inputStream = new ObjectInputStream(new
FileInputStream(fileName));
System.out.println("Reading ALL the integers");
System.out.println("in the file " + fileName);
try
{
while(true)
{
Chapter 2 Exception Handling & File Streams P a g e | 10

int anInteger = inputStream.readInt();


System.out.println(anInteger);
}
}
catch(EOFException e)
{
System.out.println("End of reading from file.");
}
inputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch(IOException e)
{
System.out.println("Problem with input from file " +
fileName);
}
}
}

package filestream;
import java.io.File;
import java.io.IOException;
public class FileOperation
{
public static void main(String[] args) throws IOException
Chapter 2 Exception Handling & File Streams P a g e | 11

{
File f = new File("Test1","xyz.txt");

boolean b = f.createNewFile();

if (b)
{
System.out.println("File is created successfully in " +
f.getAbsolutePath());
}
else
{
System.out.println("File is already existed in " +
f.getAbsolutePath());
}
System.out.println(f.canRead());
System.out.println(f.exists());
System.out.println(f.canWrite());
System.out.println(f.getName());
System.out.println(f.isFile());
System.out.println(f.isDirectory());
System.out.println(f.isAbsolute());
System.out.println(f.lastModified());
System.out.println(f.length()+ " bytes");
}
}

package serialization;
Chapter 2 Exception Handling & File Streams P a g e | 12

public class ValueTooSmallException extends Exception


{
public ValueTooSmallException()
{

public ValueTooSmallException(String message)


{
super(message);
}

package serialization;

import java.io.Serializable;

public class Account implements Serializable


{
//If you do not want individual member variables to be serialized,
while allowing the serialization of others, you can use the transient
keyword
int accountNo;
transient String accountName;
double balance;

Account(int accountNo, String accountName, double balance) throws


ValueTooSmallException
Chapter 2 Exception Handling & File Streams P a g e | 13

{
this.accountNo = accountNo;
this.accountName = accountName;

if (balance < 0)
{
throw new ValueTooSmallException("Negative Balance");
}
else
{
this.balance = balance;
}

package serialization;
import java.io.*;

public class WriteAccount


{
public static void main(String[] args) throws IOException,
ValueTooSmallException
{
Account account1 = new Account(1, "account1", 40);
Account account2 = new Account(2, "account2", 100);
Chapter 2 Exception Handling & File Streams P a g e | 14

try (FileOutputStream out = new FileOutputStream("acc.dat");


ObjectOutputStream outob = new ObjectOutputStream(out))
{
outob.writeObject(account1);
outob.writeObject(account2);
}

}
}

package serialization;
import java.io.*;

public class ReadAccount


{
public static void main(String[] args)
{
try (FileInputStream in = new FileInputStream("acc.dat");
ObjectInputStream inobj = new ObjectInputStream(in))
{

Account acc1 = (Account) inobj.readObject();


Account acc2 = (Account) inobj.readObject();

System.out.println(" 1st number:"+acc1.accountNo);


System.out.println(" 1st balance:"+acc1.balance);

System.out.println(" 2nd number:"+acc2.accountNo);


System.out.println(" 2nd balance:"+acc2.balance);
Chapter 2 Exception Handling & File Streams P a g e | 15

}
catch(IOException | ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
}
}

package filestream.random;
import java.io.RandomAccessFile;
import java.io.IOException;
public class WriteRAF
{
public static void main(String[] args) throws IOException
{
int i;
String text;
RandomAccessFile fileOut;
fileOut = new RandomAccessFile("RAFile1.dat", "rw");
for (i = 1; i < 11; i++)
{
text = "Address of " + i +" person \n";
System.out.println("offset: " + fileOut.length() );
fileOut.seek(fileOut.length());
fileOut.writeChars(text);
}
fileOut.close();
}
Chapter 2 Exception Handling & File Streams P a g e | 16

}
package filestream.random;

import java.io.*;
public class ReadRAF
{
public static void main(String[] args) throws IOException
{
char singleChar;
StringBuffer address;
RandomAccessFile fileIn;
fileIn = new RandomAccessFile("RAFile1.dat", "r");
fileIn.seek(80);
address = new StringBuffer(20);
while ((singleChar = fileIn.readChar()) != '\n')
{
address.append(singleChar);
}
System.out.println(address);
fileIn.close();
}

You might also like