我需要在程序中保存2个变量
示例:int limit;布尔值;
我使用文本字段设置limt变量值,使用切换按钮设置变量值
例如:的限制 = 5; 在 =费尔斯;
我想将这两个变量保存在文件
中当我重新运行程序时,我需要保持值 例如:的限制 = 5; 在 =费尔斯;
当我更改这些值时,需要在文件中更新
例如:限制 =我通过文本字段输入的内容和 on = true或根据我的选择显示
当我再次运行时,需要在程序中显示更改的值
答案 0 :(得分:0)
我已经制作了一个可以工作的小型Java项目。我希望它可以帮助您了解如何写入文件。首先,它检查文件是否存在。如果不是它创造它。然后它写出你的两个变量。
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) {
}
}
}