teaching machines

CS 145 Lecture 32 – File Reading and Writing

November 17, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

TODO

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