Why do I get a NullPointerException?

I have two classes in a package called compressor: Compressor and Reader. Compressor takes a file from the first command line argument (args[0]) and then attempts to read it into a byte array using an instance of Reader.

Compressor's code:
Java Code: public class Compressor { File f; public Compressor(File file) { f = file; System.out.println("File set."); } public void compress() { try { r.read(f); } catch (Exception e) { System.out.println("Caught"); e.printStackTrace(); } } public static void main(String[] args) throws IOException { String fileName = args[0]; File f = new File(fileName); Compressor c = new Compressor(f); c.compress(); } } mh_sh_highlight_all('java'); Reader's Code:
Java Code: public class Reader { FileInputStream fileIn; byte[] in; public Reader() throws IOException { fileIn = null; } public byte[] read(File file) throws IOException { long length = file.length(); in = new byte[(int) length]; fileIn = new FileInputStream(file); int offset = 0; int numRead = 0; while (offset < in.length && (numRead = fileIn.read(in, offset, in.length-offset)) >= 0) { offset = offset + numRead; } fileIn.close(); return in; } } mh_sh_highlight_all('java'); Both classes compile fine ("javac compressor/Compressor.java"), but when I try to run them on the command line with a file ("java compressor/Compressor 1") I get the following:
File set.
at compressor.Compressor.compress(Compressor.java:19)
at compressor.Compressor.main(Compressor.java:30)

Having looked up NullPointerExceptions, etc, I think that the program is not calling the actual file (named "1"), but I'm not sure why not.

Any advice on what I am doing wrong would be greatly appreciated!
Posted On: Thursday 25th of October 2012 01:51:49 AM Total Views:  158
View Complete with Replies