-3

I need to save 2 variables in my program

example:int limit; Boolean on;

I set limt variable value using a textfield and on variable value using a toggle button
ex:limit=5; on=fales;

I want to save this two variables in a file

when I re run my program i needs to keep values
ex:limit=5; on=fales;

when I changed those values it needs to be update in the file
ex:limit=what ever I enter through textfield and on= true or fales according to my choice

when I run again changed values are needs to be shown in the program

1 Answers1

0

I have made a small Java project that works and does the trick. I hope it helps you understand how to write to a file. At first it checks if the file exists. If not it creates it. Then it writes your two variables.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

public class IO_12_StackOverFlow1 {

    public static void main(String[] args) throws IOException {

        File file = new File("emptyFile.txt");

        // Checks if file does not exist. If it does not, it creates it
        if (!file.exists()) {
            FileWriter fWriter = new FileWriter(file);
            PrintWriter pWriter = new PrintWriter(fWriter);
        }

        int limit = 5; // int set to 5
        boolean on = false; // boolean false

        try (Writer writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream("emptyFile.txt"), "utf-8"))) { // sets the output where to write
                    writer.write("The speed limit is: " + limit + " and "); // writes
                    writer.write("the motor is: " + on); // continues to write
        }

        catch (IOException e) {

        }

    }

}
zypa
  • 303
  • 2
  • 13