Some Classes Used for File I/O
Textfiles
Classes and Methods for Program Output to a Textfile
PrintWriter textOutFile = new PrintWriter("somefile.txt");
PrintWriter textOutFile = new PrintWriter(new FileOutputStream("somefile.txt"));
PrintWriter textOutFile = new PrintWriter(new FileOutputStream("somefile.txt", true));
textOutFile.print()
textOutFile.println()
textOutFile.printf()
textOutFile.close()
Classes and Methods for Program Input from a Textfile
Scanner textInFile = new Scanner(new File("somefile.txt"));
textInFile.nextInt() textInFile.hasNextInt()
textInFile.nextDouble() textInFile.hasNextDouble()
textInFile.next() textInFile.hasNext()
textInFile.nextLine() textInFile.hasNextLine()
textInFile.nextByte() textInFile.hasNextByte()
textInFile.nextShort() textInFile.hasNextShort()
textInFile.nextLong() textInFile.hasNextLong()
textInFile.nextFloat() textInFile.hasNextFloat()
textInFile.nextBoolean() textInFile.hasNextBoolean()
textInFile.close()
Binary Files
Classes and Methods for Program Output to a Binary File
ObjectOutputStream binaryOutFile = new ObjectOutputStream(new FileOutputStream("somefile.dat"));
ObjectOutputStream binaryOutFile = new ObjectOutputStream(new FileOutputStream(new File("somefile.dat")));
binaryOutFile.writeInt(someInt)
binaryOutFile.writeDouble(someDouble)
binaryOutFile.writeUTF(someString)
binaryOutFile.writeObject(someSerializableObject)
binaryOutFile.writeByte(someByte)
binaryOutFile.writeShort(someShort)
binaryOutFile.writeLong(someLong)
binaryOutFile.writeFloat(someFloat)
binaryOutFile.writeBoolean(someBoolean)
binaryOutFile.close()
Classes and Methods for Program Input from a Binary File
ObjectInputStream binaryInFile = new ObjectInputStream(new FileInputStream("somefile.dat"));
ObjectInputStream binaryInFile = new ObjectInputStream(new FileInputStream(new File("somefile.dat")));
someInt = binaryInFile.readInt()
someDouble = binaryInFile.readDouble()
someString = binaryInFile.readUTF()
someSerializableObject = (appropriate_cast)binaryInFile.readObject()
someByte = binaryInFile.readByte()
someShort = binaryInFile.readShort()
someLong = binaryInFile.readLong()
someFloat = binaryInFile.readFloat()
someBoolean = binaryInFile.readBoolean()
binaryInFile.close()
A Class for Creating a File Object from Any File, and Some of Its Methods
The File
Class
File f = new File("somefile.txt");
Some Methods of the File
Class
f.exists()
f.canRead()
f.canWrite()
f.delete()
f.length()
f.getName()
f.getPath()
Some Potential I/O-Related Exceptions
java.lang.ClassNotFoundException
java.lang.NumberFormatException
java.io.EOFException
java.io.FileNotFoundException
java.io.InvalidClassException
java.io.IOException
java.io.NotSerializableException
java.io.OptionalDataException
java.io.UTFDataFormatException