「ファイル」は文字や数値を記録した電子的記録です。ここでは、Processing でファイルを作成したり、読みこむ方法を紹介します。
12,35 45,50 56,30 70,30 85,46 66,80setup()の中の loadString(<ファイル>)は文字を記録したファイルのすべての行を行単位に読みこみ、String 配列 lines[] に記録します。
String lin;
int ln;
String lines[];
void setup() {
//ファイルを文字列配列に lines 読み込む
ln=0;
lines = loadStrings("pos.txt");
}
void draw() {
lin =lines[ln];//第 ln 行を読む
// , で分割
String[] co = split(lin, ',');
if (co.length==2) {//x,y の2項目があれば
//整数に変換
int x = int(co[0]);
int y = int(co[1]);
ellipse(x, y, 3, 3);
}
ln++;
//最後まで読んだら停止
if(ln == lines.length) noLoop();
}
//ファイルを読み座標を表示
BufferedReader reader;
String line;
void setup() {
//ファイルを開く
reader = createReader("pos.txt");
}
void draw() {
line=null;
try {
//1行読む
line = reader.readLine();
}
catch (IOException e) {//エラー処理
e.printStackTrace();
println("読み取りエラー");
}
if (line == null) {
//読み取り終了
noLoop();
}
else {
// , で分割
String[] co = split(line, ',');
if (co.length==2) {
//整数に変換
int x = int(co[0]);
int y = int(co[1]);
ellipse(x, y, 3, 3);//円を表示
}
else println(line);// , なし
}
}
実行結果(ファイルの内容で異なります)
//ファイル保存
PrintWriter outfile;
void setup()
{
size(200, 200);
// ファイルを作成する
outfile = createWriter("pos.txt");
frameRate(20);
}
void draw()
{
if (mousePressed) {
ellipse(mouseX, mouseY,3,3);
// ファイルに記録する
outfile.println(mouseX + "," + mouseY);
}
}
void keyPressed() {
if(key == 's'){
outfile.flush(); //残りを出力する
outfile.close(); // ファイルを閉じる
exit(); // 終了
}
}
ファイル への実際の出力は println() の度に行うわけでなく、ある程度データが蓄積された段階で出力します。flush() は残りのデータを強制的に出力する指示です。その後、close()
でファイルを閉じます。void setup()
{
size(200, 200);
// ファイルを作成する
String path = selectOutput();
println(path);
outfile = createWriter(path);
frameRate(20);
}
///ファイルパス(windows)の例
E:\soft\processing\prIntro\SaveFile\data\pos.txt
異なるフォルダのファイルを選択して読み込むするには、selectInput() を利用します。また、個別のファイルでなく、フォルダーを選択する場合は、selectFolder()
が利用できます。//Shift JIS でファイル出力
//getBytes で文字コードを変換し、バイト出力する
String[] st= { "あいうえ", "漢字"};
byte[] crlf="\r\n".getBytes("Shift_JIS");
void setup() {
OutputStream outfile;
try {
outfile = createOutput("SJIS.txt");
//st[0]を Shift_JISコードのバイト列に変換しファイル出力
outfile.write(st[0].getBytes("Shift_JIS"));
//改行コードのバイト列をファイルに出力
outfile.write(crlf);
outfile.write(st[1].getBytes("Shift_JIS"));
outfile.write(crlf);
outfile.flush();
outfile.close();
}
catch(IOException e) {
System.out.println(e);
}
}
void keyPressed() {
if(key == 's'){
outfile.flush(); //残りを出力する
outfile.close(); // ファイルを綴じる
exit(); // 終了
}
if(key == '.'){
save("hc"+no+".png");
println("save:"+no);
no++;
}
}