Read and write data in the same txt file

edited December 2017 in How To...

hii,

Greetings,

i am beginner for processing , i stuck in between please help me out,

what i want to do *open a file(xyz.txt) read data from it *do some activity(addition,mltiplication...etc) by that data upgrade it *and store in samefile(xyz.txt)

thank you
:)gani

Answers

  • STOP SHOUTING we can read lower case...

    don't do this. read the first file, write to a second file and then rename the second file to the first file.

  • oops:( sorry can u help me with a example?

  • what do you already have?

  • To read a data from txt file

    i am using this code

                        BufferedReader reader;
                        String line;
    
                        void setup() {
                          // Open the file from the createWriter() example
                          reader = createReader("positions.txt");
                        }
    
                        void draw() {
                          try {
                            line = reader.readLine();
                          } 
                          catch (IOException e) {
                            e.printStackTrace();
                            line = null;
                          }
                          if (line == null) {
                            // Stop reading because of an error or file is empty
                            noLoop();
                          } else {
                            String[] lines = loadStrings("positions.txt");
                            println("there are " + lines.length + " lines");
                            for (int i = 0; i < lines.length; i++) {
                              println(lines[i]);
                            }
                          }
                        } 
    

    to write data in txt file

    i am using this code

            PrintWriter output;
            int i=0;
            void setup() {
              // Create a new file in the sketch directory
              output = createWriter("positions.txt"); 
            }
    
            void draw() {
              point(mouseX, mouseY);
               // Write the coordinate to the file
            }
    
            void keyPressed() {
    
              if(key=='a' || key=='A'){
              output.println("hiii"+i);// Finishes the file
             i++;
              output.flush(); // Writes the remaining data to the file
              output.close(); }
            }
    
  • you don't need a createReader if you use loadStrings() - loadStrings load all the file in one go, createReader is designed for reading a line at a time - two different things. decide which you want.

    https://processing.org/reference/createReader_.html

    https://processing.org/reference/loadStrings_.html

Sign In or Register to comment.