0

I'm trying to get Processing to randomly pick a document and print it from terminal, but so far I'm not sure how to do the first part: put filenames in an array and have Processing randomly pick filenames from the array. Any help would be appreciated!

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);

}

1 Answers1

1

If the files are in your sketch's resource directory, using loadStrings() saves a lot of effort. However, here's a more general case:

    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!");
      }
    }
kevinsa5
  • 3,301
  • 2
  • 25
  • 28