Java: Files and IO

Java.IO

The original File object

File myFile = new File(“/path/to/file”);

Methods: delete(), exists(), getAbsolutePath(), getName(), getParent, isDirectory(), isFile(), lastModified(), length(), listFiles(), mkdir(), mkdirs(), renameTo()

File Separator

System.getProperty(“file.separator”)
File.separator
File.pathSeparator

Stream vs Reader vs Writer

  • bytes → stream
  • characters → reader/writer

InputStream

  • FileInputStream
  • FilterInputStream
    • BufferedInputStream
  • ObjectInputStream

methods: close(), read(), read(byte[] b), read(byte[] b, offset, length), markSupported(), mark(readLimit), reset(), skip(n)

OutputStream

  • FileOutputStream
  • FilterOutputStream
    • BufferedOutputStream
    • PrintStream
  • ObjectOutputStream

methods: close(), write(int), write(byte[] b), write(byte[] b, offset, length), flush()

Reader

  • BufferedReader
  • InputStreamReader
    • FileReader

methods: close(), read(), read(char[] b), read(char[] b, offset, length), markSupported(), mark(readLimit), reset(), skip(long n), readLine() in BufferedReader

Writer

  • BufferedWriter
  • OutputStreamWriter
    • FileWriter
  • PrintWriter

methods: close(), write(int), write(char[] b), write(char[] b, offset, length), flush(), newLine() in BufferedWriter

Useage

Raw Streams

while( (b = in.read() ) != -1 ){
	out.write(b);
}

// “in” → input stream (b = bytes) or reader (b = char)
// “out” → output stream (b = bytes) or writer (b = char)

Buffered Streams (Reader / Writer, use char instead of byte)

byte[] bArray = new byte[256];
while( (lenRead = in.read(bArray) ) > 0 ){
	out.write(bArray, 0, lenRead);
}

String nextLineStr;
while ( ( nextLineStr = buffReader.nextLine() ) != null ){
	buffWriter.write(nextLineStr);
	buffWriter.newLine();
}

Scanner

Scanner myScanner = new Scanner(myInputStream);
while(myScanner.hasNextLine){
	String nextLine = myScanner.nextLine();
	….
}

PrintStream/Writer

format & printf methods work similar to printf in ‘C’.

  • %s – any type, string values
  • %d – integer / long
  • %f – float / double
  • %n – new line
  • %f – 6 digit post decimal
  • %.1f – 1 digit post decimal, rounded, not truncated
  • %12.8 – 12 total digits, 8 post decimal, leading space
  • %012.8 – 12 total digits, 8 post decimal, leading zero

Console I/O

  • System.in
  • System.out
  • System.err
  • Console.readLine();
  • Console.writer().printf();
  • Console.reader();

Java.NIO

Path: a new version of File.

Path myPath = Paths.get(“dir1”, “dir2”, “filename”); //→ /dir1/dir2/filename
Path myPath = Paths.get(new URI(“file//myFile.txt”) );
Path myPath = Path.of(“dir1”, “dir2”, “filename”);  //→ /dir1/dir2/filename
Path myPath = Path.of(“/dir1/dir2/filename”);  //→ /dir1/dir2/filename
Path myPath = myFile.toPath();

Path methods: getNameCount(), getName(nameCnt),subPath(start,end), getFileName(), getParent(), getRoot(), isAbsolute(), toAbsolutePath(),

path1.resolve(path2); // get me to path2 from path1
path1.relative(path2) ;
path1.normalize(); // use with equals()
path1.toRealPath(); // follow symbolic links

Files

Methods: exists(), isSameFile(), createDirectory(), createDirectories(), copy(), move(), delete(), deleteIfExists(), isDirectory(), isSymbolicLink(), isRegularFile(), isHidden(), isReadable(), isWritable(), isExecutable(), size()

Traversing directories using Streams

  • Files.list(); → Stream<Path>
  • Files.walk(); → Stream<Path>
  • Files.find(); → Stream<Path>
  • Files.lines(filePath); → a stream of the lines of a file

File Attributes (chmod style attributes)

BasicFileAttributes myAttr = Files.readAttributes(thePath, BasicFileAttributes.class);
                                 // read only
BasicFileAttributesView myAttrView
                 = Files.getFileAttributeView(thePath, BasicFileAttributesView.class);
                                 // view is updateable

Serialization

Each serializable object should

  • have a private static final long serialVersionUID [ default = 1l];
  • implement marker interface serializable
  • every member should itself be serializable or null
  • (members with ‘transient’ modifier will not be serialized)

Writing

OutputStream out = new ObjectOutputStream(myFileOutStream);
out.writeObject(theSerializableObject);

Reading

InputStream in = new ObjectInputStream(myFileInStream);
Object myObjToBeCast = in.readObject();

On rehydration

  • no constructors or initialisation
  • no-arg constructor of first non-serializable parent called