CS 145 Lecture 32 – File Reading and Writing
Agenda
- what ?s
- computer anatomy
- files
- interoperability
- persistence
- PrintWriter
- buffered I/O
- extracting out the ID3 tag from an MP3
- random access
TODO
- The next Mercy Fortnight will go into effect starting December 6. It has the following stipulations:
- You must complete and submit homework 7 before December 6. It covers the creation of custom types using objects, and our discussion this week and your book should give you sufficient background to complete it. If you choose not to participate in Mercy Fortnight, homework 7 must be turned in before December 13.
- Any previous homeworks may be resubmitted starting December 6 up to the final exam on December 17. That’s not quite a fortnight, but it’s close.
- You must inform me through email that you’ve resubmitted a homework.
- At most one resubmission may be made per day.
Code
RandomPhobia.java
package lecture1117;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
public class RandomPhobia {
public static void main(String[] args) throws FileNotFoundException {
// read in list of phobias
// reconnaissance
Scanner in = new Scanner(new File("/Users/johnch/Desktop/phobias.txt"));
int nLines = 0;
while (in.hasNextLine()) {
in.nextLine();
++nLines;
}
in.close();
// actual loading
String[] phobias = new String[nLines];
in = new Scanner(new File("/Users/johnch/Desktop/phobias.txt"));
for (int i = 0; i < nLines; ++i) {
phobias[i] = in.nextLine();
}
in.close();
// pick one at random
Random g = new Random();
int iRandom = g.nextInt(phobias.length);
System.out.println(phobias[iRandom]);
}
}
Xor.java
package lecture1117;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Xor {
public static void main(String[] args) throws FileNotFoundException {
int width = 256;
int height = 256;
PrintWriter out = new PrintWriter("/Users/johnch/Desktop/xor.ppm");
out.println("P3");
out.println(width + " " + height);
out.println(255);
for (int r = 0; r < height; ++r) {
for (int c = 0; c < width; ++c) {
out.printf("%d %d %d%n", (r ^ c) % 256, r % 256, c % 256);
}
}
out.close();
}
}
ID3.java
package lecture1117;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ID3 {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile(new File("/Users/johnch/Desktop/mystery.mp3"), "r");
raf.seek(raf.length() - 125);
byte[] stuff = new byte[30];
raf.read(stuff);
System.out.println(new String(stuff));
raf.read(stuff);
System.out.println(new String(stuff));
raf.read(stuff);
System.out.println(new String(stuff));
raf.close();
}
}
Haiku
on recording life:
Born with a GoPro
Hiccups, first word, baseball games
Egging, judge, jail time
Born with a GoPro
Hiccups, first word, baseball games
Egging, judge, jail time