Ch 09 – Files
Supanit Angsirikul
Text File
createWriter( )
PrintWriter pw = createWriter("test.txt"); // PrintWriter is used for writing text to a text-output stream, and the created instance is named pw.
for (int i = 0; i < 10; i++) // createWriter is used to create a file in the sketch folder, and an object from PrintWriter named pw is used to write data to the file.
pw.println(i + ""); // println() of PrintWriter is used to write data to the stream and move to a new line.
pw.close(); // Finishes the file
BufferedReader br = null; // BufferedReader is used to create an object for reading data line by line.
try {
br = createReader("test.txt"); // createReader is used to create a BufferedReader object for reading data line by line.
String s = null;
while ( (s = br.readLine ()) != null) // readLine() of BufferedReader is used to read data from a file.
print(s + " " );
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
Create a file : text.txt
Java 7, Autoclosable Object and Resource Block�but not available in Processing yet.
try (BufferedReader br = createReader("test.txt"); ) {
String s = null;
while ( (s = br.readLine ()) != null)
print(s + " " );
} catch (IOException e) {
e.printStackTrace();
}
Data (Raw) File
import java.io.*;
OutputStream os = createOutput("test.data"); //Create a data file named test.data using an OutputStream as the output stream for the data.
DataOutputStream dos = new DataOutputStream(os); // Create a data transmission channel named dos to send data into os.
try {
for (int i = 0; i < 10; i++)
dos.writeInt(i);
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
dos.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
Data (Raw) File
InputStream is = createInput("test.data"); //Create an InputStream as a channel for data to flow in from the file test.data.
DataInputStream dis = new DataInputStream(is); //Create a DataInputStream to read data from the InputStream.
try {
int x;
while (true) {
x = dis.readInt();
print(x + " " );
}
} catch(EOFException e) {
try {
dis.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
} catch(IOException e) {
e.printStackTrace();
}
Binary File
int max = 10;
byte b[] = new byte[max*4];
int k = 0;
for (int i = 0; i < max; i++) {
b[k++] = (byte) ((i >> 24) & 0xFF); //>>shift bit to the right
b[k++] = (byte) ((i >> 16) & 0xFF);
b[k++] = (byte) ((i >> 8) & 0xFF);
b[k++] = (byte) (i & 0xFF);
}
saveBytes( "test.bin", b);
b = loadBytes("test.bin");
k = 0;
int a[] = new int[max];
for (int i = 0; i < max; i++)
a[i] = b[k++] << 24 | b[k++] << 16 | b[k++] << 8 | b[k++];
printArray(a);
// println(java.util.Arrays.toString(a));
Exlore file at Sketch -> show sketch folder
loadStrings(file_name) - Read from a file into an array of strings.
String sa[] = { "John", "Jack", "Joe", "Jim", "Jame" };
PrintWriter pw = createWriter("test.str");
for (String n : sa)
pw.println("Hello! " + n); // write the data into PrintWriter
pw.close();
String lines[] = loadStrings("test.str");
printArray(lines); //print data in lines array to Console
loadXML(file_name)
PrintWriter pw = createWriter("students.xml");
pw.println("<?xml version='1.0'?>");
pw.println("<students>");
pw.println("<student id='1' name='John Rambo' gpa='3.5'/>");
pw.println("<student id='2' name='Jack Ripper' gpa='4.0'/>");
pw.println("<student id='3' name='Joe Green' gpa='1.1'/>");
pw.println("</students>");
pw.close();
XML xml = loadXML("students.xml");
XML xa[] = xml.getChildren("student");
printArray(xa);
// for (XML x : xa)
// println(x.getInt("id") + "," + x.getString("name") + "," + x.getFloat("gpa"));
JSON
JSONObject jo = new JSONObject();
jo.setInt("id", 1);
jo.setString("name", "John Rambo");
jo.setFloat("gpa", 3.5);
saveJSONObject(jo, "students.json");
println(jo.toString());
JSONObject jx = loadJSONObject("students.json");
print(jx.getInt("id") + "," + jx.getString("name") + "," + jx.getFloat("gpa"));
JSONArray
JSONObject john = new JSONObject();
john.setInt("id", 1);
john.setString("name", "John Rambo");
john.setFloat("gpa", 3.5);
JSONObject jack = new JSONObject();
jack.setInt("id", 2);
jack.setString("name", "Jack Ripper");
jack.setFloat("gpa", 4.0);
JSONArray ja = new JSONArray();
ja.setJSONObject(0, john);
ja.setJSONObject(1, jack);
saveJSONArray(ja, "students.json");
println(ja.toString());
JSONArray jx = loadJSONArray("students.json");
println(jx);
for (int i = 0; i < jx.size(); i++) {
JSONObject s = jx.getJSONObject(i);
println(s.getInt("id") + "," + s.getString("name") + "," + s.getFloat("gpa"));
}
loadXML(file_name)
PrintWriter pw = createWriter("students.xml");
pw.println("<?xml version='1.0'?>");
pw.println("<students>");
pw.println("<student id='1' name='John Rambo' gpa='3.5'/>");
pw.println("<student id='2' name='Jack Ripper' gpa='4.0'/>");
pw.println("<student id='3' name='Joe Green' gpa='1.1'/>");
pw.println("</students>");
pw.close();
XML xml = loadXML("students.xml");
XML xa[] = xml.getChildren("student");
printArray(xa);
// for (XML x : xa)
// println(x.getInt("id") + "," + x.getString("name") + "," + x.getFloat("gpa"));
PDF File
import processing.pdf.*;
boolean savePDF = false;
void setup() {
beginRecord(PDF, "test.pdf" );
size(640, 480);
background(255);
smooth();
rectMode(CENTER);
noStroke();
}
void draw() {
fill(random(255), random(255), random(255), random(255));
pushMatrix();
translate( random( width ), random( height ) );
rotate(radians(random(360)));
rect(0, 0, random(60), random(60));
popMatrix();
}
void keyPressed() {
if (key == 's') {
endRecord();
noLoop();
print("Save.");
}
}
PShape
PShape ps;
void setup() {
// copy /data to /mysketch
ps = loadShape("data/tiger.svg");
// size(300, 200);
size(640, 480);
// size(800, 600);
shape(ps, 0, 0);
}
void draw() { }
void keyPressed() {
if (key == 'm') {
stroke(0);
strokeWeight(5);
noFill();
arc(350, 380, 100, 50, 0, PI);
}
else if (key == 's') {
save("tiger.png");
}
}
tiger.svg download at https://sites.google.com/a/rsu.ac.th/supanit23/csc451
save picture at processing-4.1.1-widows-x64/processing-4.1.1/data
save(file_name)
float a = 0, s = 12, cx, cy, d = 200;
void setup() {
size(600, 400);
background(255);
noFill();
smooth();
cx = width/2; cy = height/2;
}
void draw() {
pushMatrix();
translate(cx, cy);
rotate(a);
ellipse(0, 0, 2*d, d);
popMatrix();
a += PI/s;
d -= 10;
if (d < 3) {
stroke(random(255), random(255), random(255), random(255));
cx = random(width); cy = random(height);
d = random(90);
s = random(12);
}
}
void keyPressed() {
if (key == 'n') {
noLoop();
}
else if (key == 'p') {
save("test.png");
}
else if (key == 'j') {
save("test.jpg");
}
else if (key == 'i') {
save("test.tif");
}
else if (key == 'a') {
save("test.tga");
}
}
save(file_name)
saveFrame("name-####.png")
void setup() {
size(640, 480);
background(255);
smooth();
noStroke();
}
void draw() {
fill(random(255), random(255), random(255), random(255));
ellipse( random(width), random(height), random(5, 50), random(5, 50));
}
void keyPressed() {
if (key == 's')
saveFrame("test-####.png");
else
noLoop();
}
PImage
PImage
PImage
size(200, 200);
PImage im = loadImage(“data/android2.jpg");
im.resize(width, height);
// resize the image to the frame size
background(im);
save("android-Saved.png");
Show Image
image(image, x, y) display image at x, y (upper left corner).
image(image, x, y, w, h)
or
background(image)
void setup() {
size( 250, 250 );
strokeWeight(4);
// point(20, 20);
}
void draw() { }
void keyPressed() {
if (key == '1') {
PImage im = loadImage("data/android1.png");
image(im, 20, 20);
}
else if (key == '2') {
PImage im = loadImage("data/android1.png");
image(im, 20, 20, width/2, height/2);
}
else if (key == '3') {
PImage im = loadImage("data/android2.jpg");
image(im, 20, 20);
}
else if (key == '4') {
PImage im = loadImage("data/bird3.png");
background(255);
image(im, 20, 20);
}
else if (key == '5') {
PImage im = loadImage("data/bird1.png");
im.resize(width, height);
background(im);
}
}
imageMode(mode)
PImage im;
void setup() {
size(200, 200);
im = loadImage(“data/bird3.png");
}
void draw() { }
void keyPressed() {
if (key == '1') {
imageMode(CORNER);
background(255);
image(im, width/2, height/2, 100, 100);
}
else if (key == '2') {
imageMode(CORNERS);
background(255);
image(im, 20, 20, 120, 120);
}
else if (key == '3') {
imageMode(CENTER);
background(255);
image(im, width/2, height/2, 100, 100);
}
}
Assignment # ch9
read more