CS 202 - Computer Science II - Fall 2004
Reading Files
Loyola College >
Department of Computer Science >
Dr. James Glenn >
CS 202 >
Examples and Lecture Notes >
Reading Files
StatementCount.java
import java.io.*;
/**
* Reads a Java source code file and displays a complexity count. The
* complexity count is obtained by counting the lines that contain
* opening braces or semi-colons. This is intended to approximate the
* number of "real" lines of code in a program.
*
* @author Jim Glenn
* @version 0.1 10/25/2004
*/
public class StatementCount
{
/**
* Displays the complexity count of a Java source code file.
* The names of the files to count should be given in the
* array argument.
*
* @param args contains the names of the files to count
*/
public static void main(String[] args) throws IOException
{
for (int file = 0; file < args.length; file++)
{
// open file
BufferedReader in
= new BufferedReader(new FileReader(args[file]));
// initialize complexity count
int count = 0;
// read lines until end of file
String line;
while ((line = in.readLine()) != null)
if (line.indexOf('{') != -1 || line.indexOf(';') != -1)
count++;
// output final complexity count
if (args.length > 1)
System.out.print(args[file] + ": ");
System.out.println(count);
}
}
}
PNMPanel.java
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
public class PNMPanel extends JPanel
{
/**
* The image to display in this panel.
*/
protected Image im;
/**
* The name of the file containing the image this panel will
* display.
*/
protected String filename;
/**
* A message to display in lieu of the image. The message is
* displayed before the file loads or of there is an error.
*/
protected String message;
/**
* A flag that is set when an error has occurred reading the file.
* This is intended to be used to signla that we should not try to
* load the image even if <CODE>im</CODE> is <CODE>null</CODE>.
*/
protected boolean error;
/**
* Creates a panel that displays the image in the file with the
* given name. If there is an error reading the file, an
* error message will be displayed.
*
* @param fname the name of the file containing the image data to display
*/
public PNMPanel(String fname)
{
message = "Loading " + fname;
error = false;
filename = fname;
}
/**
* Reads the image data for this panel. Sets <CODE>im</CODE> to
* <CODE>null</CODE> if there is an error reading from the file;
* in such cases <CODE>message</CODE> is set accordingly.
*/
private void readImage()
{
try
{
BufferedReader infile
= new BufferedReader(new FileReader(filename));
// read format and check that it is P3
String format = infile.readLine();
if (!format.equals("P3"))
throw new Exception("Unexpected PNM file format: " + format);
// read size and split into width and height
String size = infile.readLine();
StringTokenizer tok = new StringTokenizer(size);
int width = Integer.parseInt(tok.nextToken());
int height = Integer.parseInt(tok.nextToken());
setPreferredSize(new Dimension(width, height));
// read and ignore maximum (we assume it is 255)
String max = infile.readLine();
// make an image
im = createImage(width, height);
Graphics g = im.getGraphics();
// read pixel data, one pixel per line, and stuff it into
// the image
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
// read the color component values
String color = infile.readLine();
tok = new StringTokenizer(color);
int red = Integer.parseInt(tok.nextToken());
int green = Integer.parseInt(tok.nextToken());
int blue = Integer.parseInt(tok.nextToken());
// set the pixel in the image
g.setColor(new Color(red, green, blue));
g.drawLine(x, y, x, y);
}
}
catch (FileNotFoundException e)
{
im = null;
error = true;
message = "Could not find " + filename;
}
catch (IOException e)
{
im = null;
error = true;
message = "Error reading " + filename;
}
catch (Exception e)
{
im = null;
error = true;
message = "Bad file format in " + filename;
}
}
/**
* Draws this panel.
*
* @param g the context to draw in
*/
public synchronized void paint(Graphics g)
{
// This isn't really the best way to do this but will do for
// now -- the method is synchronized so if we get several repaints
// before we load the image we won't start reading the file
// for each one.
if (error)
{
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.drawString(message, 0, 10);
}
if (im == null)
{
g.drawString(message, 0, 10);
readImage();
}
else
g.drawImage(im, 0, 0, null);
}
/**
* Demo of PNMPanel.
*
* @param args contains the name of the file to display
*/
public static void main(String[] args)
{
JPanel im;
if (args.length == 0)
im = new PNMPanel("arsha_in_box_p3.pnm");
else
im = new PNMPanel(args[0]);
JFrame win = new JFrame();
win.getContentPane().add(im);
win.setSize(400, 400);
win.setVisible(true);
}
}
PNMPanel2.java
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
public class PNMPanel2 extends JPanel
{
/**
* The image to display in this panel.
*/
protected Image im;
/**
* The name of the file containing the image this panel will
* display.
*/
protected String filename;
/**
* A message to display in lieu of the image. The message is
* displayed before the file loads or of there is an error.
*/
protected String message;
/**
* A flag that is set when an error has occurred reading the file.
* This is intended to be used to signla that we should not try to
* load the image even if <CODE>im</CODE> is <CODE>null</CODE>.
*/
protected boolean error;
/**
* Creates a panel that displays the image in the file with the
* given name. If there is an error reading the file, an
* error message will be displayed.
*
* @param fname the name of the file containing the image data to display
*/
public PNMPanel2(String fname)
{
message = "Loading " + fname;
error = false;
filename = fname;
}
/**
* Reads the image data for this panel. Sets <CODE>im</CODE> to
* <CODE>null</CODE> if there is an error reading from the file;
* in such cases <CODE>message</CODE> is set accordingly.
*/
private void readImage()
{
try
{
// open the file and prepare to tokenize it
BufferedReader infile
= new BufferedReader(new FileReader(filename));
StreamTokenizer tok = new StreamTokenizer(infile);
tok.commentChar('#');
// read format and check that it is P3
if (tok.nextToken() != StreamTokenizer.TT_WORD || !tok.sval.equals("P3"))
throw new Exception("Unexpected PNM file format: " + filename);
// read width, height, and max value (checking that they
// are numbers)
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int width = (int)(tok.nval);
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int height = (int)(tok.nval);
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int max = (int)(tok.nval);
// make an image
im = createImage(width, height);
Graphics g = im.getGraphics();
// read pixel data, one pixel per line, and stuff it into
// the image
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
// read the color component values
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int red = (int)(tok.nval);
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int green = (int)(tok.nval);
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int blue = (int)(tok.nval);
// set the pixel in the image
g.setColor(new Color(red, green, blue));
g.drawLine(x, y, x, y);
}
}
catch (FileNotFoundException e)
{
im = null;
error = true;
message = "Could not find " + filename;
}
catch (IOException e)
{
im = null;
error = true;
message = "Error reading " + filename;
}
catch (Exception e)
{
im = null;
error = true;
message = "Bad file format in " + filename;
}
}
/**
* Draws this panel.
*
* @param g the context to draw in
*/
public synchronized void paint(Graphics g)
{
// This isn't really the best way to do this but will do for
// now -- the method is synchronized so if we get several repaints
// before we load the image we won't start reading the file
// for each one.
if (error)
{
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.drawString(message, 0, 10);
}
if (im == null)
{
g.drawString(message, 0, 10);
readImage();
}
else
g.drawImage(im, 0, 0, null);
}
/**
* Demo of PNMPanel.
*
* @param args contains the name of the file to display
*/
public static void main(String[] args)
{
JPanel im;
if (args.length == 0)
im = new PNMPanel2("arsha_in_box_p3.pnm");
else
im = new PNMPanel2(args[0]);
JFrame win = new JFrame();
win.getContentPane().add(im);
win.setSize(400, 400);
win.setVisible(true);
}
}
PNMPanel3.java
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
public class PNMPanel3 extends JPanel
{
/**
* The image to display in this panel.
*/
protected Image im;
/**
* The name of the file containing the image this panel will
* display.
*/
protected String filename;
/**
* A message to display in lieu of the image. The message is
* displayed before the file loads or of there is an error.
*/
protected String message;
/**
* A flag that is set when an error has occurred reading the file.
* This is intended to be used to signla that we should not try to
* load the image even if <CODE>im</CODE> is <CODE>null</CODE>.
*/
protected boolean error;
/**
* Creates a panel that displays the image in the file with the
* given name. If there is an error reading the file, an
* error message will be displayed.
*
* @param fname the name of the file containing the image data to display
*/
public PNMPanel3(String fname)
{
message = "Loading " + fname;
error = false;
filename = fname;
}
/**
* Reads the image data for this panel. Sets <CODE>im</CODE> to
* <CODE>null</CODE> if there is an error reading from the file;
* in such cases <CODE>message</CODE> is set accordingly.
*/
private void readImage()
{
try
{
// open the file and prepare to tokenize it
RandomAccessFile infile = new RandomAccessFile(filename, "r");
// read the header and save it in a string for tokenizing
String header = "";
int headerLines = 0;
while (headerLines < 3)
{
String line = infile.readLine();
header += line + "\n";
if (!line.startsWith("#"))
headerLines++;
}
// tokenize the header
StreamTokenizer tok = new StreamTokenizer(new StringReader(header));
tok.commentChar('#');
// read format and check that it is P6
if (tok.nextToken() != StreamTokenizer.TT_WORD || !tok.sval.equals("P6"))
throw new Exception("Unexpected PNM file format: " + filename);
// read width, height, and max value (checking that they
// are numbers)
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int width = (int)(tok.nval);
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int height = (int)(tok.nval);
if (tok.nextToken() != StreamTokenizer.TT_NUMBER)
throw new Exception("Unexpected PNM file format: " + filename);
int max = (int)(tok.nval);
// make an image
im = createImage(width, height);
Graphics g = im.getGraphics();
// read pixel data, three bytes per pixel, and stuff it into
// the image
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
// read the color component values
int red = infile.readUnsignedByte();
int green = infile.readUnsignedByte();
int blue = infile.readUnsignedByte();
// set the pixel in the image
g.setColor(new Color(red, green, blue));
g.drawLine(x, y, x, y);
}
}
catch (FileNotFoundException e)
{
im = null;
error = true;
message = "Could not find " + filename;
}
catch (IOException e)
{
im = null;
error = true;
message = "Error reading " + filename;
}
catch (Exception e)
{
e.printStackTrace(System.err);
im = null;
error = true;
message = "Bad file format in " + filename;
}
}
/**
* Draws this panel.
*
* @param g the context to draw in
*/
public synchronized void paint(Graphics g)
{
// This isn't really the best way to do this but will do for
// now -- the method is synchronized so if we get several repaints
// before we load the image we won't start reading the file
// for each one.
if (error)
{
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.drawString(message, 0, 10);
}
if (im == null)
{
g.drawString(message, 0, 10);
readImage();
}
else
g.drawImage(im, 0, 0, null);
}
/**
* Demo of PNMPanel.
*
* @param args contains the name of the file to display
*/
public static void main(String[] args)
{
JPanel im;
if (args.length == 0)
im = new PNMPanel3("arsha_in_box_p3.pnm");
else
im = new PNMPanel3(args[0]);
JFrame win = new JFrame();
win.getContentPane().add(im);
win.setSize(400, 400);
win.setVisible(true);
}
}
This code can also be downloaded from the files
StatementCount.java,
PNMPanel.java,
PNMPanel2.java,
and PNMPanel3.java.