我正在尝试让Processing随机选择一个文档并从终端打印它,但到目前为止我不知道如何做第一部分:将文件名放在一个数组中并让Processing从数组中随机选择文件名。任何帮助将不胜感激!
String[] document = new String[3];// = loadStrings("/Users/saraswatikalwani/Desktop/Hello.txt");
int n = 1;
document[0] = "/Users/saraswatikalwani/Desktop/Hello.txt";
document[1] = "/Users/saraswatikalwani/Desktop/How.txt";
document[2] = "/Users/saraswatikalwani/Desktop/Bye.txt";
//String document = [];
//String []document = new String[3];
//int n = int(random(0,1));
//var document = [];
//int n = //randomnumber
//String choosen = document[n];// = random(document);
void setup() {
size(640, 360);
//document[0] = "/Users/saraswatikalwani/Desktop/Hello.txt";
// document[1] = "/Users/saraswatikalwani/Desktop/How.txt";
//document[2] = "/Users/saraswatikalwani/Desktop/Bye.txt";
}
void draw() {
}
void mousePressed() {
String[] params = {"lpr", "document[1]" };
exec(params);
}
答案 0 :(得分:1)
如果文件位于草图的资源目录中,则使用loadStrings()
可以节省大量精力。但是,这是一个更普遍的案例:
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
ArrayList<File> files;
void setup(){
files = new ArrayList<File>();
File folder = new File("/Users/saraswatikalwani/Desktop")
File[] fileList = folder.listFiles();
for(File f : fileList){
if(f.isFile()){
if(f.getName().endsWith(".txt")) files.add(f);
}
}
println(files);
}
void draw(){}
void mousePressed(){
int randIndex = (int) random(files.size());
try {
BufferedReader reader = new BufferedReader(new FileReader(files.get(randIndex)));
String line = "Printing: "+files.get(randIndex).getName();
while(line != null){
println(line);
line = reader.readLine();
}
} catch(IOException e) { //could be error calling readLine() or a filenotfound exception
println("Error!");
}
}