2017-01-15 35 views
-3

我需要保存2個變量在我的程序中如何保存文件中的變量更新和加載

例如:int limit;布爾開啓;

我使用文本框和上變量值使用切換按鈕設置LIMT變量值
例如:極限 = 5; on = fales;

我想,當我重新運行我的程序我需要保持價值
前此兩個變量在一個文件

節省:限制 = 5; on = fales;

當我改變它需要更新文件中的這些值
例如:限制 =什麼都我通過文本框輸入和 = true或費爾斯根據自己的選擇

當我運行再次更改的值需要在程序中顯示

+0

添加您的代碼。你應該搜索文件讀取和寫入Java。 –

+0

你被困在某個特定的東西上,還是你期望我們爲你寫代碼? – shmosel

+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) { 

     } 

    } 

} 
相關問題